ref属性介绍

在React典型的数据流中,修改子组件都是通过重新渲染新的props来完成的。但是,当你想要在数据流之外修改子组件,就需要React提供的ref属性。

ref在元素中声明,代表着该元素提供了可以操作的DOM操作(React组件中提供的是虚拟DOM操作)。

使用场景

  • 处理focus、text selection
  • 处理交互动画
  • 与第三方DOM库集成

使用方式

  1. 使用回调函数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    class CustomTextInput extends React.Component {
    constructor(props) {
    super(props);
    this.focusTextInput = this.focusTextInput.bind(this);
    }
    focusTextInput() {
    this.textInput.focus();
    }
    render() {
    return (
    <div>
    <input
    type="text"
    ref={(input) => { this.textInput = input; }} />
    <input
    type="button"
    value="Focus the text input"
    onClick={this.focusTextInput}
    />
    </div>
    );
    }
    }

点击按钮后,input输入框会focus。

React会在组件加载后调用ref回调函数,在componentDidMount函数周期之前invoke或在componentDidUpdate周期中执行。

需要注意的是,由于 this.refs.[refName] 属性获取的是真实 DOM ,所以必须等到虚拟 DOM 插入文档以后,才能使用这个属性,否则会报错。

  1. 使用ref属性名
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    var MyComponent = React.createClass({
    handleClick: function() {
    this.refs.myTextInput.focus();
    },
    render: function() {
    return (
    <div>
    <input type="text" ref="myTextInput" />
    <input type="button" value="Focus the text input" onClick={this.handleClick} />
    </div>
    );
    }
    });

React不建议用refs,因为有许多弊端。https://github.com/facebook/react/pull/8333#issuecomment-271648615