reactjs – React设置焦点在渲染后的输入
发布时间:2020-12-15 07:20:29 所属栏目:百科 来源:网络整理
导读:在渲染组件后,在特定文本字段上设置焦点的反应方法是什么? 文档似乎建议使用refs,例如: 在render函数的输入字段上设置ref =“nameInput”,然后调用: this.refs.nameInput.getInputDOMNode().focus(); 但我应该在哪里叫这个?我试过几个地方,但我不能
在渲染组件后,在特定文本字段上设置焦点的反应方法是什么?
文档似乎建议使用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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |