React refs usage tutorial, reactrefs usage tutorial
Ref is an attribute in React. When the render function returns an instance of a component, you can add a ref attribute to a virtual DOM node in render, as shown in the following code:
<body> <script type="text/jsx"> var App = React.createClass({ render: function() { return ( <div> <input type="text" placeholder="input something..." ref="input" /> </div> ); } }); React.render( <App />, document.body ); </script> </body>
In the above Code, the render function returns only one <div> tag, and only one <input> tag in <div>. In the <input> tag attribute, A ref attribute is added. The official document explains the ref attribute as follows:
Ref attribute
React supports a very special attribute. You can bind it to any component output by render. This special attribute allows you to reference the corresponding backing instance returned by the render ). In this way, you can always get the correct instance at any time.
What is the purpose of setting the ref attribute for the <input> tag? The following is an explanation in the official document:
In other code (typical event processing code), obtain the backing instance through this. refs, just like this. refs. input. "Input" is the value of the ref attribute set for the <input> label above.
Through the ref attribute, we can also get the real DOM node corresponding to the virtual DOM. There are two ways to get the real DOM node, as shown in the following code:
<Input type = "text" ref = "username"/> // The following four methods can be used to obtain the real DOM node var usernameDOM = this through ref. refs. username. getDOMNode (); var usernameDOM = React. findDOMNode (this. refs. username); var usernameDOM = this. refs ['username']. getDOMNode (); var usernameDOM = React. findDOMNode (this. refs ['username']);
Here is a demo to learn how to use ref:
The effect of running the demo in the browser is as follows:
Enter any number ranging from 1 to 10 in the top input box to get the focus in the corresponding input box of the following 10 input boxes. For example, after entering 3, the following 3rd input boxes will get the focus immediately, the ref attribute is used here. The Code is as follows:
<! DOCTYPE html>
In the render function, 10 input boxes are added to the body of the html document. The ref attribute of each input box is set to ["index" + index, then, in the handleChange function in the top input box, obtain the input number, obtain the value of the ref attribute, and find the corresponding real DOM node based on the value of the ref attribute, then let the DOM node get the focus.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.