React Refs


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

This special property allows you to reference the corresponding backing instance returned by render(). This ensures that you always get the correct instance at any time.

Usage method

Bind a ref attribute to the return value of render:

<input ref="myInput" />

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

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

Complete example

You can use this to get the current React component, or use ref to get the reference of the component. The example is as follows:

Example

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>php中文网 React 实例</title>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react.min.js"></script>
    <script src="http://static.php.cn/assets/react/react-0.14.7/build/react-dom.min.js"></script>
    <script src="http://static.php.cn/assets/react/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
    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')
    );
    </script>
  </body>
</html>

Run instance»

Click the "Run instance" button to view the online instance

In the instance, we obtained the reference to the supporting instance of the input box , the input box gets focus after the child clicks the button.

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