如果你以前使用过 React,你可能会熟悉旧的 API,其中的 ref
属性是字符串,如 ref={'textInput'}
,并且 DOM 节点的访问方式为this.refs.textInput
。我们建议不要这样做,因为字符串引用有以下问题,并且被认为是遗留问题。字符串 refs 在 React v16 版本中被移除。
this.refs
上的字符串引用的作用及其类型。Callback refs 对静态分析更友好。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} />
}
}