跳到主内容

React如何使input自动聚焦?

· 1分钟阅读

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.

解决方法

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.

或者

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"));