在React中,ref={callback}和ref="myInput"有什么不同?

20

“并保存该组件以备将来使用,正如它所说的那样,我们可以这样做。” 它在所有示例中都有:ref = {(input) => {this.textInput = input;}} - Felix Kling
ref="myInput" => 用于访问未来使用的 ref - Khalid Azam
3个回答

18

使用ref={callback}的区别是,React将管理引用存储的责任交回给您。当您使用ref="sometext"时,在React内部,它必须在类上创建一个refs属性,并将所有ref="sometext"语句添加到其中。

虽然拥有一个简单的this.refs.sometext访问组件很好,但在React方面,清理这些refs属性时很困难且容易出错。让React将组件传递给您并让您处理是否要存储它会更容易。

根据React文档所述:

当组件挂载时,React将使用DOM元素调用ref回调函数,并在卸载组件时使用null调用它。

这实际上是一个非常巧妙的想法,通过在卸载时传递null并再次调用回调函数,您可以自动清除引用。

要实际使用它,您只需从任何函数中访问它,如下所示:

class CustomTextInput extends React.Component {
  constructor(props) {
    super(props);
    this.focus = this.focus.bind(this);
  }

  focus() {
    // Explicitly focus the text input using the raw DOM API
    this.textInput.focus();
  }

  render() {
    // Use the `ref` callback to store a reference to the text input DOM
    // element in this.textInput.
    return (
      <div>
        <input
          type="text"
          ref={(input) => { this.textInput = input; }} />
        <input
          type="button"
          value="Focus the text input"
          onClick={this.focus}
        />
      </div>
    );
  }
}

您在 ref 上设置的回调函数将会接收组件作为第一个参数,在这个例子中,'this' 关键字将是当前类 'CustomTextInput'。在回调函数中设置 this.textInput 将可使 textInput 在其它所有函数中(如 focus())可用。

具体示例

Dan Abermov 的推文 显示了一个使用 ref 回调函数更好的情况。

enter image description here

更新

根据 Facebook 文档,使用字符串作为 refs 已被视为遗留 API,他们“建议改用回调模式或 createRef API。”


4
当您像这样分配ref={callback},例如<input type="text" ref={(input) => {this.textInput = input}}/>时,您实际上是将名称为textInput的ref保存以备将来使用。因此,我们可以使用回调方法而不是使用ref="myInput",然后稍后访问组件,如this.textInput,而不是使用this.refs.myInput
以下是一个演示,我们在按钮单击上使用ref访问输入值的示例。

class App extends React.Component {
  constructor(){
    super();
  }
  handleClick = () => {
    console.log(this.textInput.value);
  }
  render() {
    return (
      <div>
        <input type="text" ref={(input) => {this.textInput = input}}/>
        <button type="button" onClick={this.handleClick}>Click</button>
      </div>
    )
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.4/react-dom.min.js"></script>
<div id="app"></div>


-1

在React 16.3中,您可以使用React.createRef() API:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
  }

  render() {
    return <div ref={this.myRef} />;
  }
}

3
过时不正确。最新的文档显示ref函数仍然是一种有效的处理ref的方式,Facebook表示它“可以更精细地控制何时设置和取消ref”。虽然将字符串用作refs被认为是遗留问题。 - Frank

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接