reactjs – React设置焦点在渲染后的输入

在渲染组件后,在特定文本字段上设置焦点的反应方法是什么?

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

在render函数的输入字段上设置ref =“nameInput”,然后调用:

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

但我应该在哪里叫这个?我试过几个地方,但我不能让它工作。

你应该在componentDidMount和 refs callback中做。这样的东西
componentDidMount: function(){
   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>

相关文章

一、前言 在组件方面react和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...