在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
本卡普的解决方案在打字稿
React 16.8 +功能组件- useFocus钩子
export const useFocus = (): [React.MutableRefObject<HTMLInputElement>, VoidFunction] => {
const htmlElRef = React.useRef<HTMLInputElement>(null);
const setFocus = React.useCallback(() => {
if (htmlElRef.current) htmlElRef.current.focus();
}, [htmlElRef]);
return React.useMemo(() => [htmlElRef, setFocus], [htmlElRef, setFocus]);
};
其他回答
如果你只是想在React中自动对焦,这很简单。
<input autoFocus type="text" />
而如果你只是想知道把代码放在哪里,答案是componentDidMount()。
v014.3
componentDidMount() {
this.refs.linkInput.focus()
}
在大多数情况下,您可以为DOM节点附加一个引用,而完全避免使用findDOMNode。
在这里阅读API文档:https://facebook.github.io/react/docs/top-level-api.html#reactdom.finddomnode
<input type="text" autoFocus />
总是先尝试简单和基本的解决方案,对我来说很有效。
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>
);
};
请注意,这些答案对我来说都没有用material-ui TextField组件。如何将焦点设置为一个materialUI TextField?我费了好大劲才让它起作用:
const focusUsernameInputField = input => {
if (input) {
setTimeout(() => {input.focus()}, 100);
}
};
return (
<TextField
hintText="Username"
floatingLabelText="Username"
ref={focusUsernameInputField}
/>
);
这不再是最好的答案。从v0.13开始,这个。在某些奇怪的情况下,refs可能在AFTER componentDidMount()运行之前不可用。
只需将autoFocus标签添加到输入字段,如上面的FakeRainBrigand所示。