Seven. Get the real DOM node

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.