React component refs detailed explanation
As the name implies, ref can be seen as a reference to a component, or as an identifier. As a component attribute, its attribute value can be a string or a function.
In fact, the use of ref is not mandatory. Even in the scenarios where it is applicable, it is not necessary to use it, because the functions implemented by using ref can also be converted into other methods. However, since ref has its applicable scenarios, it means that ref has its own advantages. Regarding this point and the applicable scenarios of ref, the official document says:
After returning the UI structure from the render method, you may want to break out of the constraints of the React virtual DOM and call certain methods on the component instance returned by render. Generally speaking, this is not necessary for the data flow in the application, because the active data (Reactive data) flow always ensures that the latest props are passed to each child output from render(). However, there are still several scenarios where it is necessary or beneficial to use this approach: finding the DOM tag (think of it as a DOM ID) of the rendered component, using React components in a large non-React application, or converting your existing code to React .
Let's look at a scenario like this (the following example is often used to explain ref, so it can be seen that the scenario described below should be relatively classic): through an event, the value of the <input /> element is set to an empty string, and then the <input /> element is focused.
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
this.setState({userInput: ''}); // Set the value to an empty string
// We want to get focus here
},
render: function() {
return (
<div>
<input
value={this.state.userInput}
onChange={this.handleChange}
/>
<input type="button"
value="Reset And Focus"
onClick={this.clearAndFocusInput}
/>
</div>
);
}
});
In the above example, we have implemented the button to notify the input element to set the value to an empty string, but we have not yet implemented the input element to gain focus. This is a bit difficult to implement because what is returned in render() is not a combination of actual subcomponents, but only a description of a specific instance at a specific time. This sentence feels quite confusing. In fact, render returns a virtual DOM , not a real DOM. Therefore, we do not need to focus only on those components returned from render().
That said, it doesn't help us much in getting the focus. To get the focus, we need to use ref. As mentioned above, there are two types of ref values, one is a string and the other is a callback function.
Ref string attributes
React supports a special property that you can add to any component returned by render (). This means marking the component returned by render() so that you can easily locate the component instance. This is what ref does.
The form of ref is as follows
<input ref="myInput" />
To access this instance, you can access it through this.refs:
this.refs.myInput
In previous versions, we can access the component's DOM through React.findDOMNode(this.refs.myInput). But now, the findDOMNode function has been abandoned, and you can directly use this.refs.myInput to access it.
ref callback function
The ref attribute can also be a callback function instead of a name. This function will be executed immediately after the component is mounted. The referenced component will be used as a parameter of the function, and the function can use the component parameter immediately or save it for later use.
Its form is also relatively simple:
render: function() {
return <TextInput ref={(c) => this._input = c} } />;
},
componentDidMount: function() {
this._input.focus();
},
or
render: function() {
return (
<TextInput
ref={function(input) {
if (input != null) {
input.focus();
}
}} />
);
},
It should be noted here that when the reference component is uninstalled and the ref is changed, the parameter value of the previous ref will be null. This will effectively prevent memory leaks. So there will be an if judgment in the above code:
if(input != null){
input.focus();
}
The above introduces the usage scenarios and methods of ref. Now let's complete the above example to achieve the function of getting focus .
var App = React.createClass({
getInitialState: function() {
return {userInput: ''};
},
handleChange: function(e) {
this.setState({userInput: e.target.value});
},
clearAndFocusInput: function() {
this.setState({userInput: ''}); // Clear the input
// We wish to focus the <input /> now!
if (this.refs.myTextInput !== null) {
this.refs.myTextInput.focus();
}
},
render: function() {
return (
<div>
<input
value={this.state.userInput}
onChange={this.handleChange}
ref=”myTextInput”
/>
<input
type="button"
value="Reset And Focus"
onClick={this.clearAndFocusInput}
/>
</div>
);
}
});
ReactDOM.render(
<App />,
document.getElementById('content')
);
In this example, the render function returns a description of an <input /> instance. But the actual instance is obtained through this.refs. myTextInput. As long as a child component returned by render has ref="myTextInput", this.refs. myTextInput will get the correct instance.
The above is all about ref. For more information about ref, please refer to Ref to Components .
This is all we have to say about ref. I hope this article will be helpful to you.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Two ways to implement React's ref callback function
Publish Date:2025/03/02 Views:89 Category:React
-
Two ways to implement ref callback function in React
Details that need to be paid attention to when compiling react with webpack
Publish Date:2025/03/02 Views:197 Category:React
-
It is very convenient to compile and package react using webpack. Both need to be installed using npm. However, if you do not pay attention to the installation location of webpack and react parser babel during use, problems will occur during
Common terms used in React Virtual DOM
Publish Date:2025/03/02 Views:174 Category:React
-
In all the terms of React, there are five core types that we need to remember. These five types are ReactElement / ReactElement Factory ReactNode ReactComponent / ReactComponent Class
React Getting Started createClass Usage Instructions
Publish Date:2025/03/02 Views:50 Category:React
-
Before using React.createClass, lets look at the official explanation ReactClass createClass(object specification) Create a component class with a given specification (the specification is the object specification). This component implement
React.createElement method usage details
Publish Date:2025/03/02 Views:193 Category:React
-
The React.createElement method creates and returns a ReactElement element of a given type. The type parameter can be an html tag name string or a ReactClasss. This type parameter is required for createElement.
React Factory Method - Detailed Explanation of createFactory
Publish Date:2025/03/02 Views:88 Category:React
-
React.createFactory returns a function for generating ReactElement of a given type, similar to React.createElement. The type parameter can be an html tag name (for example: "div", "li", etc.) or a ReactClass object.
React Project Management
Publish Date:2025/03/02 Views:123 Category:React
-
In the article "Beginner's Guide to React - Building a React Runtime Environment", we only introduced how to build a React runtime environment, which is actually how to reference the React library. But I think it is still a bit confusing for
React Getting Started - Building a React Operating Environment
Publish Date:2025/03/02 Views:62 Category:React
-
React, a front-end framework developed by Facebook, is very popular. There are two ways to run React, one is to use npm, and the other is not to use npm. These involve react-dom, babel, webpack, etc.
How to refresh the page in Vue
Publish Date:2025/03/01 Views:85 Category:Vue
-
Vue is a popular JavaScript framework that provides many convenient tools and methods for building web applications. In Vue, page updates are usually achieved through data binding and responsive systems. But sometimes you need to refresh the