Javascript 在React组件中存储多个引用与按ID查询DOM

Javascript 在React组件中存储多个引用与按ID查询DOM,javascript,reactjs,performance,Javascript,Reactjs,Performance,我正在react中构建表单,并希望在提交后自动聚焦到第一个无效字段。为此,我需要访问无效字段的引用并对其调用.focus()。我的问题是,在构造函数中存储多个引用更好(性能更好),还是只需在每个字段上附加一个ID并查询DOM以获取引用 constructor(props) { super(props); this.state = this.props.entry; this.submitForm = this.submitForm.bind(this); this

我正在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();
vs

本质上,是否不需要存储对每个表单输入的引用,而不是按ID查询一次DOM?

如果将
包装到组件中,则可以建立单个引用并委托功能:

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
class TextInput扩展了React.PureComponent{
构造函数(){
超级()
this.input=React.createRef();
}
焦点=()=>{
this.input.current.focus()
}
render(){
返回()
}
}
//其他地方。。。
const text_input=React.createElement(TextInput)
text_input.focus()#=>调用上面定义的'focus'方法

我的意思是,这实际上只是将createRef推到管道的下游。您仍然在为您需要的每个输入创建一个引用,只是将其包装在PureComponent中,而不是附加到父窗体。我想我要问的是,与按ID查询DOM相比,创建大量引用的性能是否更差。从实现的角度来说,ref是相当轻量级的,您可以有1000个ref,而不会注意到。我以为你的目标是干掉你的构装师。在任何情况下,你都应该为这类事情找出一些小的组件。
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