渲染后将焦点放在输入上

本文探讨了在React中如何实现在组件渲染后自动聚焦到特定的输入字段。介绍了使用refs和componentDidMount方法,以及更简便的autoFocus属性来实现这一功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自: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();} } />

More info 更多信息

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值