ChatGPT解决这个技术问题 Extra ChatGPT

How to set focus on an input field after rendering?

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.


J
Jude Allred

@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=...

Note that in jsx it's autoFocus (capital F) unlike plain old html which is case-insensitive.


Note that in jsx its autoFocus (capital F) unlike plain old html which is case-insensitive.
Very Good, Got here after a long fruitless search :) FYI - I ended up using React.DOM.input({ type: 'text', defaultValue: content, autoFocus: true, onFocus: function(e) {e.target.select();} })
I find that autoFocus only works on first page render. See codepen.io/ericandrewlewis/pen/PbgwqJ?editors=1111 the input should be focused after 3 seconds.
+1 for this method. It's worth mentioning that this doesn't just use HTML5 unreliable autofocus attribute, it actually uses focus() on DOM mount in react-dom so it's quite reliable.
Not only "for convenience" but also if your component is a functional component.
D
Dhiraj

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(

{ this.nameInput = input; }} defaultValue="will focus" />
); } } ReactDOM.render(, document.getElementById('app'));


This is the correct answer, but it did not work for me as my component first renders nothing, until another button is clicked. This meant that it was already mounted, so I had to add this.refs.nameInput.getDOMNode().focus(); in componentDidUpdate instead of componentDidMount.
Why, when element.focus() is called, does it put the cursor at the beginning of the input? I saw this (what I consider a) bug in my app, in chrome, actually in a