React component refs Usage Details, reactrefs Usage Details

Source: Internet
Author: User

React component refs Usage Details, reactrefs Usage Details

As the name suggests, the ref can be used as a reference or an identifier for a component. As a component property, its attribute value can be a string or a function.

In fact, the use of ref is not necessary. Even in the applicable scenarios, it is not optional, because the functions implemented by using ref can also be converted into other methods for implementation. However, since ref has its own applicable scenarios, that is to say, ref has its own advantages. The applicable scenarios of this and ref are described in the official document as follows:

After returning the UI structure from the render method, you may want to rush out of the React virtual DOM restriction and call some methods on the component instance returned by the render. Generally, this is unnecessary for data Flow in the application, because the active data stream always ensures that the latest props is passed to each () in the output sublevel. However, there are still several scenarios where this method is required or helpful: to find the DOM tag of the rendered component (which can be considered as the dom id ), use the React component in a large non-React application or convert your existing code into a React.

Let's look at this scenario (The following example is often used for ref explanation. It can be seen that the scenario described below is more classic ): an event is used to set the value of the <input/> element 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.tar get. value}) ;}, clearAndFocusInput: function () {this. setState ({userInput: ''}); // set the value to an empty string // here you want to achieve focus}, 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 a button to notify the input element to set the value to a null string, but it has not yet implemented a focus for the input element. This is difficult to implement because the returned result in render () is not a combination of actual child components, but a description of a specific instance at a specific time. In fact, render returns a virtual DOM instead of a real DOM. Therefore, we do not need to focus on those components returned from render.

Speaking of this, it is not very helpful for us to achieve the focus. To achieve the focus function, we need to use ref. As mentioned above, there are two types of ref values: string and callback.

Ref string attributes

React supports a special attribute. You can add this attribute to any component returned through render. This means that the component returned by the render () is marked so that the component instance can be conveniently located. This is the role of ref.

The ref format is as follows:

<input ref="myInput" />

To access this instance, you can use this. refs to access:

this.refs.myInput

In previous versions, we can access the component DOM through React. findDOMNode (this. refs. myInput. But now, the findDOMNode function has been abandoned. You can directly use this. refs. myInput for access.

Ref callback function

The ref attribute can also be a callback function rather than 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. This function can immediately use this component parameter, and of course save it for future use.

The format 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();     }    }} />  );},

Note that when the reference component is uninstalled and the ref changes, the value of the previous ref parameter is null. This effectively prevents Memory leakage. So in the above Code, if judgment will be made:

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

The usage scenarios and methods of ref are described above. The example above is complete 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 (      <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 the <input/> instance. However, the real instance is obtained through this. refs. myTextInput. As long as a sub-component returned by render carries ref = "myTextInput", this. refs. myTextInput will get the correct instance.

Above is all the content of ref,

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.