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

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

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

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

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


当前回答

ReactDOMComponent:不要访问DOM节点的.getDOMNode();相反,直接使用节点。这个DOM节点由App渲染。

应该是

componentDidMount: function () {
  this.refs.nameInput.focus();
}

其他回答

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

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

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

你应该在componentDidMount和refs回调中做。就像这样

componentDidMount(){
   this.nameInput.focus(); 
}

class App extends React.Component{ componentDidMount(){ this.nameInput.focus(); } render() { return( <div> <input defaultValue="Won't focus" /> <input ref={(input) => { this.nameInput = input; }} defaultValue="will focus" /> </div> ); } } ReactDOM.render(<App />, document.getElementById('app')); <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script> <div id="app"></div>

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

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

@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:

<input autoFocus name=...

注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。