何时使用 inputRef.current 而不是 this.inputRef React.js?

mr *_*bug 4 reference reactjs

我对两种语法来访问react文档中的引用感到困惑...我想知道的是何时使用inputRef.current来访问引用而不是react中的this.inputRef

Est*_*ask 5

正如其他答案提到的,currentref 属性是由 创建的React.createRef(),它最初在 React 16 中不可用,并在 React 16.3 中引入。

一般来说,它是旧语法(React 15、React 16.0 到 16.2):

<input ref={ref => this.inputRef = ref}/>
...
this.inputRef.focus()
Run Code Online (Sandbox Code Playgroud)

对比新语法(React 16.3 及更高版本):

inputRef = React.createRef();
...
<input ref={this.inputRef}/>
...
this.inputRef.current.focus()
Run Code Online (Sandbox Code Playgroud)

新语法引入了一个可用的模式,也可以在旧的 React 版本中使用:

inputRef = { current: null };
...
<input ref={ref => this.inputRef.current = ref}/>
...
this.inputRef.current.focus()
Run Code Online (Sandbox Code Playgroud)

重要的区别是React.createRef()创建包含唯一属性 的 ref 对象current。这是一种保持 ref 对象引用永久的模式,即使current属性中的 ref 正在更改。这样 ref 对象就可以通过引用传递,即使current最初是null

这以前是一种反模式,主要是因为 ref 是易失性的:

const ComponentThatAcceptsRefs = ({ inputRef }) => (
  <button onClick={() => inputRef.focus() }>Focus</button>
);
Run Code Online (Sandbox Code Playgroud)

<input ref={ref => this.inputRef = ref}/>
<ComponentThatAcceptsRefs inputRef={this.inputRef}/>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当它作为 prop 传递时,它是未定义的。这需要将inputRefprop 设置为 getter 函数才能使其工作getInputRef={() => this.inputRef}

虽然 ref 对象也可以实现同样的效果(演示):

const ComponentThatAcceptsRefs = ({ inputRef }) => (
  <button onClick={() => inputRef.current.focus() }>Focus</button>
);
Run Code Online (Sandbox Code Playgroud)

inputRef = React.createRef();
...
<input ref={this.inputRef}/>
<ComponentThatAcceptsRefs inputRef={this.inputRef}/>
Run Code Online (Sandbox Code Playgroud)

React 中可能有更传统和实用的方法,不依赖于 refs,但可以使用 ref 对象来做到这一点。