本文翻译自:Set focus on input after render
What's the react way of setting focus on a particular text field after the component is rendered? 在呈现组件之后,将焦点设置在特定文本字段上的反应方式是什么?
Documentation seems to suggest using refs, eg: 文档似乎建议使用引用,例如:
Set ref="nameInput"
on my input field in the render function, and then call: 在渲染函数的输入字段中设置ref="nameInput"
,然后调用:
this.refs.nameInput.getInputDOMNode().focus();
But where should I call this? 但是我应该在哪里称呼它呢? I've tried a few places but I cannot get it to work. 我已经尝试了几个地方,但无法正常工作。
#1楼
参考:https://stackoom.com/question/1xDYw/渲染后将焦点放在输入上
#2楼
You can put that method call inside the render function. 您可以将该方法调用放入render函数中。 Or inside the life cycle method, componentDidUpdate
或在生命周期方法内, componentDidUpdate
#3楼
You should do it in componentDidMount
and refs callback
instead. 您应该在componentDidMount
执行此操作,并refs callback
代替。 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>
#4楼
@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted: @Dhiraj的答案是正确的,为方便起见,您可以使用autoFocus道具在安装时让输入自动聚焦:
<input autoFocus name=...
Note that in jsx it's autoFocus
(capital F) unlike plain old html which is case-insensitive. 请注意,在jsx中,它是autoFocus
(大写F),不像普通的旧html,它不区分大小写。
#5楼
This is not longer the best answer. 这不再是最佳答案。 As of v0.13, this.refs
may not available until AFTER componentDidMount()
runs, in some odd cases. 从v0.13 this.refs
,在某些奇怪的情况下, this.refs
componentDidMount()
运行之前,可能无法使用this.refs
。
Just add the autoFocus
tag to your input field, as FakeRainBrigand showed above. 只需将autoFocus
标记添加到您的输入字段中,如上面的FakeRainBrigand所示。
#6楼
Ref. 参考 @Dave's comment on @Dhiraj's answer; @Dave对@Dhiraj答案的评论; an alternative is to use the callback functionality of the ref attribute on the element being rendered (after a component first renders): 一种替代方法是在要渲染的元素上使用ref属性的回调功能(在组件首次渲染之后):
<input ref={ function(component){ React.findDOMNode(component).focus();} } />