Refs to introduce
React supports a very special attribute called Ref that you can use to bind to any component of the render() output. This special property allows you to quote the corresponding backing instance returned by Render (). This ensures that the correct instance is always available at all times.
// Example <input ref="myInput"/ > / / accesslet input = this.refs.myInput;
let inputValue = input.value;
let inputRect = input.getBoundingClientRect();
Copy the code
Main uses of Refs
- Do some animated interaction
- Playback of media controls
- Get focus, get text, etc
Two ways to create Refs
- Use the React. CreateRef () API
import React from 'react';
exportdefault class RefApp extends React.Component { constructor(props) { super(props); this.input = React.createRef(); // Create a ref to store the input DOM element this.copy= this.copy. Bind (this); }copy() {the console. The log (enclosing input) / / access to create refs enclosing input. The current. The select (); // Use current to get the current element}render() {
return (
<div>
<input ref={this.input} type="text"></input> <button onClick={this.copy. Bind (this)} >Copy the code
- Retrieve the DOM by calling Refs
Ref is the callback function
import React from 'react';
exportdefault class RefApp extends React.Component{ constructor(props){ super(props); this.copy= this.copy.bind(this); this.input = null; } // Copy the text contentcopy(){
this.input.select();
}
render() {return} <input ref={e=>this.input=e} <input ref={e=>this.input=e}type="text"></input> <button onClick={this.copy} >Copy the code
Ref is a string (not recommended)
copy(){
console.log(this.refs);
this.refs.inputEle.select();
}
render() {return<div> {/* ref is a string, which is obtained from the refs attribute of the component object"inputEle" type="text"></input> <button onClick={this.copy} >Copy the code
The parent component retrieves the DOM from the child component through refs
function CustomTextInput(props) {
return (
<div>
<input ref={props.inputRef} />
</div>
);
}
class Parent extends React.Component {
render() {
return( <CustomTextInput inputRef={el => this.inputElement = el} /> ); }}Copy the code
In the example above, Parent passes its ref callback to CustomTextInput as a special inputRef, which the CustomTextInput passes to input via the ref attribute. Finally, this.inputelement in Parent will be set to the DOM node corresponding to the input element in CustomTextInput.