Latest web development tutorials

React Refs

React to support a very special propertyRef, you can use to bind to the render () on any component of the output.

This special property allows you to reference render () returns an instance of the corresponding support (backing instance). This ensures that at any time is always to get the correct instance.

Instructions

Binding a ref attribute to render the return value:

<input ref="myInput" />

In other code examples to obtain support through this.refs:

var input = this.refs.myInput;
var inputValue = input.value;
var inputRect = input.getBoundingClientRect();

Complete example

You can get by using this current React assembly, or use the ref to obtain a reference component, examples are as follows:

var MyComponent = React.createClass({
  handleClick: function() {
    // 使用原生的 DOM API 获取焦点
    this.refs.myInput.focus();
  },
  render: function() {
    //  当组件插入到 DOM 后,ref 属性添加一个组件的引用于到 this.refs
    return (
      <div>
        <input type="text" ref="myInput" />
        <input
          type="button"
          value="点我输入框获取焦点"
          onClick={this.handleClick}
        />
      </div>
    );
  }
});

ReactDOM.render(
  <MyComponent />,
  document.getElementById('example')
);

try it"

Example, we get a reference to an example of the support the input box, click the button to enter the sub-frame gets the focus.

We can also use getDOMNode () method to get the DOM element