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

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

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

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

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


当前回答

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

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

其他回答

这不再是最好的答案。从v0.13开始,这个。在某些奇怪的情况下,refs可能在AFTER componentDidMount()运行之前不可用。

只需将autoFocus标签添加到输入字段,如上面的FakeRainBrigand所示。

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

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} />

根据更新后的语法,你可以使用this.myRref.current.focus()

阅读几乎所有的答案,但没有看到getRenderedComponent().props.input

设置文本输入参考

this.refs.username.getRenderedComponent () .props.input.onChange(”);