为什么 String Refs 被弃用?
如果你以前使用过 React,你可能会熟悉旧的 API,其中的 ref
属性是字符串,如 ref={'textInput'}
,并且 DOM 节点的访问方式为this.refs.textInput
。我们建议不要这样做,因为字符串引用有以下问题,并且被认为是遗留问题。字符串 refs 在 React v16 版本中被移除。
-
它们强制 React 跟踪当前执行的组件。这是有问题的,因为它使 React 模块有状态,这会导致在 bundle 中复制 React 模块时会导致奇怪的错误。
-
它们是不可组合的 - 如果一个库把一个 ref 传给子元素,则用户无法对其设置另一个引用。
-
它们不能与静态分析工具一起使用,如 Flow。Flow 无法猜测出
this.refs
上的字符串引用的作用及其类型。Callback refs 对静态分析更友好。 -
使用 "render callback" 模式(比如: ),它无法像大多数人预期的那样工作。
class MyComponent extends Component { renderRow = (index) => { // This won't work. Ref will get attached to DataTable rather than MyComponent: return <input ref={'input-' + index} />; // This would work though! Callback refs are awesome. return <input ref={input => this['input-' + index] = input} />; } render() { return <DataTable data={this.props.data} renderRow={this.renderRow} /> } }
如何创建?
Refs 是使用 React.createRef()
方法创建的,并通过 ref
属性添加到 React 元素上。为了在整个组件中使用refs,只需将 ref 分配给构造函数中的实例属性
class MyComponent extends React.Component {
constructor(props) {
super(props)
this.myRef = React.createRef()
}
render() {
return <div ref={this.myRef} />
}
}