渲染后如何将焦点设置在输入字段上? [英] How to set focus on an input field after rendering?
本文介绍了渲染后如何将焦点设置在输入字段上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在组件渲染后将焦点设置在特定文本字段上的反应方式是什么?
文档似乎建议使用引用,例如:
在渲染函数中在我的输入字段上设置 ref="nameInput"
,然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我应该在哪里称呼它?我已经尝试了几个地方,但我无法让它工作.
解决方案
你应该在 componentDidMount
和 refs callback
代替.像这样
componentDidMount(){this.nameInput.focus();}
class App extends React.Component{componentDidMount(){this.nameInput.focus();}使成为() {返回(<div><输入defaultValue="不会聚焦"/><输入ref={(输入)=>{ this.nameInput = input;}}defaultValue="将聚焦"/>
);}}ReactDOM.render(
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></脚本><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script><div id="app"></div>
What's the react way of setting focus on a particular text field after the component is rendered?
Documentation seems to suggest using refs, e.g:
Set ref="nameInput"
on my input field in the render function, and then call:
this.refs.nameInput.getInputDOMNode().focus();
But where should I call this? I've tried a few places but I cannot get it to work.
解决方案
You should do it in componentDidMount
and refs callback
instead. Something like this
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>
这篇关于渲染后如何将焦点设置在输入字段上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文