在组件渲染后,react如何设置聚焦在特定文本字段上?

文档似乎建议使用参考,例如:

在渲染函数的输入字段上设置ref="nameInput",然后调用:

this.refs.nameInput.getInputDOMNode().focus(); 

但是我该把它叫什么呢?我在几个地方试过了,但都不行。


当前回答

如果你只是想在React中自动对焦,这很简单。

<input autoFocus type="text" />

而如果你只是想知道把代码放在哪里,答案是componentDidMount()。

v014.3

componentDidMount() {
    this.refs.linkInput.focus()
}

在大多数情况下,您可以为DOM节点附加一个引用,而完全避免使用findDOMNode。

在这里阅读API文档:https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode

其他回答

您可以将该方法调用放在呈现函数中。或者在生命周期方法中,componentDidUpdate

由于这个错误有很多原因,我想我也会发布我所面临的问题。对我来说,问题是我将我的输入呈现为另一个组件的内容。

export default ({ Content }) => {
  return (
  <div className="container-fluid main_container">
    <div className="row">
      <div className="col-sm-12 h-100">
        <Content />                                 // I rendered my inputs here
      </div>
    </div>
  </div>
  );
}

这是我调用上述组件的方式:

<Component Content={() => {
  return (
    <input type="text"/>
  );
}} />

这一点对我很有用:

<input autoFocus={true} />

从React 0.15开始,最简洁的方法是:

<input ref={input => input && input.focus()}/>

这是正确的方法,如何自动对焦。当你使用callback而不是string作为ref value时,它会被自动调用。你得到了你的ref,而不需要使用getDOMNode触摸DOM

render: function() {
  return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
  this._input.focus();
},