Components are not real DOM nodes. It is the data structure that exists in memory. Called Virtual DOM. Only when it is inserted into the document will it become the true DOM.
According to the design of react. All the DOM changes. Are first taken under the virtual DOM. Then in the part that will actually change, the reaction is on the real DOM. This algorithm is called Domdiff. He can greatly improve the performance of the Web page.
But sometimes you need to get the real DOM node from the component. The ref attribute is used.
<! DOCTYPE html>
<script src= "Js/react.js" ></script>
<script src= "Js/react-dom.js" ></script>
<script src= "Js/browser.min.js" ></script>
<body>
<div id= "Example" ></div>
<script type= "Text/babel" >
var mycomponent = React.createclass ({
Handleclick:function () {
This.refs.myTextInput.focus ();
},
Render:function () {
Return (
<div>
<input type= "text" ref= "Mytextinput"/>
<input type= "button" value= "Focus the text input" Onclick={this.handleclick}/>
</div>
)
}
})
Reactdom.render (
<mycomponent/>
document.getElementById ("Example")
)
</script>
</body>
The child nodes of the component MyComponent in the code above have a text input box to get the user's input.
At this point, you must obtain the real DOM node. The virtual node cannot be entered by the user.
In order to do this, the text input box must have a ref attribute. Then this.refs[ refName
] will return to this true DOM node.
It's important to note that. Because This.refs[refname] gets the real DOM node. So you have to wait until the virtual DOM is inserted into the document before you can use this property, or you will get an error.
In the code above. The callback function that specifies the click event for the component. Ensures that the This.refs[refname] property is not read until the Click event occurs in the real DOM
Seven. Get the real DOM node