Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 渲染后将焦点放在输入上(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.

(我已经尝试了几个地方,但无法正常工作。)

  ask by Dave translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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,它不区分大小写。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...