React Refs

React supports a very special property, Ref, that you can use to bind to any component of the render() output.

This particular property allows you to refer to the corresponding support instance (backing instance) returned by render(). T his ensures that the right instances are always created at all times.

The value of the ref property can be available as a string or as a function.

How to use it

Bind a ref property to the return value of the render:

<input ref="myInput" />

In other code, get the support instance through this.refs:

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

The full instance

You can get the current React component by using this, or you can use ref to get a reference to the component, 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 out . . .

In the instance, we get a reference to the support instance of the input box, and the sub-click the button and the input box gets the focus.

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