如何在React中使用hooks在页面加载时聚焦特定组件?
如何在React中使用hooks在页面加载时聚焦特定组件?
在组件渲染后,设置特定文本字段的焦点有什么React方法?
文档似乎建议使用 refs ,例如:
在 render 函数中设置 ref=\"nameInput\"
,然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但我应该在哪里调用它呢?我已经尝试了几个地方,但无法使其工作。
admin 更改状态以发布 2023年5月22日
你应该在 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'));