在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
使用React Hooks / Functional组件和Typescript,你可以使用useRef钩子和HTMLInputElement作为useRef的泛型参数:
import React, { useEffect, useRef } from 'react';
export default function MyComponent(): JSX.Element {
const inputReference = useRef<HTMLInputElement>(null);
useEffect(() => {
inputReference.current?.focus();
}, []);
return (
<div>
<input ref={inputReference} />
</div>
);
}
或者如果使用reactstrap,将inputReference提供给innerRef而不是ref:
import React, { useEffect, useRef } from 'react';
import { Input } from 'reactstrap';
export default function MyComponent(): JSX.Element {
const inputReference = useRef<HTMLInputElement>(null);
useEffect(() => {
inputReference.current?.focus();
}, []);
return (
<div>
<Input innerRef={inputReference} />
</div>
);
}
其他回答
由于这个错误有很多原因,我想我也会发布我所面临的问题。对我来说,问题是我将我的输入呈现为另一个组件的内容。
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"/>
);
}} />
没有自动对焦的简单解决方案:
<input ref={ref => ref && ref.focus()}
onFocus={(e)=>e.currentTarget.setSelectionRange(e.currentTarget.value.length, e.currentTarget.value.length)}
/>
ref触发focus,然后触发onFocus计算结束并相应地设置游标。
如果你只是想在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
你不需要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所示。