在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
重点关注功能组件使用createRef
给使用功能组件的开发人员。这似乎很合适。点击按钮后,焦点发生在inputfield上。我也附上了CodeSandbox链接。
import React from 'react';
export default function App() {
const inputRef = React.createRef();
return <>
<input ref={inputRef} type={'text'} />
<button onClick={() => {if (inputRef.current) { inputRef.current.focus() }}} >
Click Here
</button>
</>
}
https://codesandbox.io/s/blazing-http-hfwp9t
其他回答
@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:
<input autoFocus name=...
注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。
你应该在componentDidMount和refs回调中做。就像这样
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>
这一点对我很有用:
<input autoFocus={true} />
在尝试了上面的许多选项后,没有成功,我发现这是因为我禁用了输入,然后启用了输入,导致焦点丢失。
我有一个道具sendingAnswer将禁用输入,而我轮询后端。
<Input
autoFocus={question}
placeholder={
gettingQuestion ? 'Loading...' : 'Type your answer here...'
}
value={answer}
onChange={event => dispatch(updateAnswer(event.target.value))}
type="text"
autocomplete="off"
name="answer"
// disabled={sendingAnswer} <-- Causing focus to be lost.
/>
一旦我拆除了瘫痪的道具,一切又开始工作了。
React 16.3增加了一个新的方便的方法来处理这个问题,在组件的构造函数中创建一个ref,并像下面这样使用它:
class MyForm extends Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focus();
}
render() {
return(
<div>
<input ref={this.textInput} />
</div>
);
}
}
有关React的更多细节。createRef,你可以在React博客中查看这篇文章。
更新:
从React 16.8开始,可以在函数组件中使用useRef钩子来实现相同的结果:
import React, { useEffect, useRef } from 'react';
const MyForm = () => {
const textInput = useRef(null);
useEffect(() => {
textInput.current.focus();
}, []);
return (
<div>
<input ref={textInput} />
</div>
);
};