在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
你不需要getInputDOMNode??在这种情况下……
当组件被挂载时,只需简单地获取ref和focus()它——componentDidMount…
import React from 'react';
import { render } from 'react-dom';
class myApp extends React.Component {
componentDidMount() {
this.nameInput.focus();
}
render() {
return(
<div>
<input ref={input => { this.nameInput = input; }} />
</div>
);
}
}
ReactDOM.render(<myApp />, document.getElementById('root'));
其他回答
这不再是最好的答案。从v0.13开始,这个。在某些奇怪的情况下,refs可能在AFTER componentDidMount()运行之前不可用。
只需将autoFocus标签添加到输入字段,如上面的FakeRainBrigand所示。
您可以将该方法调用放在呈现函数中。或者在生命周期方法中,componentDidUpdate
本卡普的解决方案在打字稿
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]);
};
由于这个错误有很多原因,我想我也会发布我所面临的问题。对我来说,问题是我将我的输入呈现为另一个组件的内容。
export default ({ Content }) => {
return (
<div className="container-fluid main_container">
<div className="row">
<div className="col-sm-12 h-100">
<Content /> // I rendered my inputs here
</div>
</div>
</div>
);
}
这是我调用上述组件的方式:
<Component Content={() => {
return (
<input type="text"/>
);
}} />
@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:
<input autoFocus name=...
注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。