Use instance sharing for react component refs

Source: Internet
Author: User
Ref as the name implies, we know that it can be Shini is a reference to a component, or it can be said to be an identity. As a property of a component, its property value can be a string or it can be a function. This article mainly and you introduce the use of react component refs, small series feel very good, and now share to everyone, but also for everyone to do a reference. Follow the small series together to see it, hope to help everyone.

In fact, the use of ref is not required. Even in its applicable scenario, it is not an option, as the functionality implemented with ref can also be translated into other methods. However, since ref has its intended scenario, it means that ref has its advantages. For this and ref scenarios, the official documentation says:

After returning the UI structure from the Render method, you may want to flush out the limitations of the React virtual DOM and invoke some methods on the component instance returned by render. In general, this is not necessary for the flow of data in the application because the active data stream always ensures that the latest props is passed to each of the reactive from the render () output. However, there are still several scenarios where it is necessary or useful to find the DOM markup for the rendered component (which can be considered the identifier ID of the DOM), to use the react component in a large non-react application, or to convert your existing code into react.

Let's take a look at a scenario like this (the following example is often used for ref's explanation, the scenario described below should be more classic): By an event, the value of the <input/> element is set to an empty string, and then the <input/> element gets the focus.


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        //here want to implement get focus     },  render:function () {   return (    <p>     <input      Value={this.state.userinput}      Onchange={this.handlechange}     />          <input type= "button"           Value= "Reset and Focus"           onclick={this.clearandfocusinput}        />    </p>   );}  );

In the example above, we have implemented a click button to notify the INPUT element to set the value to an empty string, but there is no implementation to get the INPUT element focus. This is difficult to implement because the return in render () is not a combination of actual subcomponents, but a description of a specific instance of a particular time. This sentence feels quite around, in fact, the render return is the virtual DOM, not the real DOM. So we don't need to focus only on those components that are returned from render ().

That said, there's not much help in how we get the focus. To achieve the focus we need to use ref. We mentioned above that there are two types of values for ref, one is a string and one is a callback function.

Properties on ref strings

React supports a special property that you can add to any component returned through render (). This means that the component that is returned by the render () is tagged to make it easy to locate the component instance. This is the role of ref.

The form of ref is as follows


<input ref= "Myinput"/>

To access this instance, you can visit through This.refs:


This.refs.myInput

In previous releases, we were able to access the DOM of the component through React.finddomnode (This.refs.myInput). But now, the Finddomnode function has been discarded and can be accessed directly using This.refs.myInput.

Ref callback function

The ref attribute can also be a callback function and not a name. This function will be executed immediately after the component is mounted. The referenced component will be used as an argument to the function, which can use the component parameters immediately, or it can be saved for later use.

The form is also relatively simple:


Render:function () {  return <textinput ref={(c) = = This._input = c}}/>;},componentdidmount:function () {
  this._input.focus ();},

or a


Render:function () {  return (   <textinput    ref={function (input) {     if (input! = null) {      Input.focus ();}}}    />  );},

It is important to note that when this reference component is unloaded and this ref changes, the parameter value of the previous ref will be null. This will effectively prevent the memory from leaking out. So in the above code there will be an if judgment:


if (input! = null) {     input.focus ();}

The usage scenarios and methods of ref are described above, and we will complement the above example to achieve the focus function


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 (<p> <input value={this.state.userinput} OnC          Hange={this.handlechange} ref= "Mytextinput"/> <input type= "button"  Value= "Reset and Focus" Onclick={this.clearandfocusinput}/> </p>); }}); Reactdom.render (<app/>, document.getElementById (' content ')); 

In this example, the render function returns a description of the <input/> instance. But the real example is through this.refs. Mytextinput get. As long as a child component returned by render has ref= "Mytextinput", This.refs. Mytextinput will get to the correct instance.

Related recommendations:

Explain how to use refs to locate the DOM in Vue undefined

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.