我正在 React 中构建一个表单,并希望在提交后自动聚焦于第一个无效字段。为此,我需要访问无效字段的引用并对其调用 .focus()
。那么我的问题是,在构造函数中存储多个引用更好(性能更高)还是只将 ID 附加到每个字段并查询 DOM 以获取引用。
constructor(props) {
super(props);
this.state = this.props.entry;
this.submitForm = this.submitForm.bind(this);
this.field1 = React.createRef();
this.field2 = React.createRef();
this.field3 = React.createRef();
this.field4 = React.createRef();
}
...
this.field3.focus();
对比
document.getElementById(`form_${fieldId}`).focus();
本质上,是否没有必要存储对每个表单输入的引用,而不是通过 ID 查询一次 DOM?
最佳答案
如果你包装<input>
在一个组件中,你可以建立一个单一的 ref 并委托(delegate)功能:
class TextInput extends React.PureComponent {
constructor() {
super()
this.input = React.createRef();
}
focus = () => {
this.input.current.focus()
}
render() {
return(<input ref={this.input} />)
}
}
// elsewhere...
const text_input = React.createElement(TextInput)
text_input.focus() #=> calls the `focus` method defined above
关于javascript - 在 React 组件中存储多个引用 vs 通过 ID 查询 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52653486/