如何在渲染后将焦点设置在输入字段上?
如何在渲染后将焦点设置在输入字段上?
在组件呈现后,设置特定文本字段焦点的 react 方法是什么?
文档似乎建议使用 refs,例如:
在 render 函数中设置 ref =“nameInput”
在我的输入字段上,然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但我应该在哪里调用它?我尝试了几个地方,但是我无法让它工作。
admin 更改状态以发布 2023年5月21日
你应该在 componentDidMount
和 refs 回调函数
中去做。类似这样:
componentDidMount(){ this.nameInput.focus(); }
class App extends React.Component{ componentDidMount(){ this.nameInput.focus(); } render() { return( { this.nameInput = input; }} defaultValue="will focus" /> ); } } ReactDOM.render(, document.getElementById('app'));