在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
如果你只是想在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
其他回答
您可以将该方法调用放在呈现函数中。或者在生命周期方法中,componentDidUpdate
根据更新后的语法,你可以使用this.myRref.current.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>
);
}
从React 0.15开始,最简洁的方法是:
<input ref={input => input && input.focus()}/>
你可以在这里查看更新的版本
componentDidMount() {
// Focus to the input as html5 autofocus
this.inputRef.focus();
}
render() {
return <input type="text" ref={(input) => { this.inputRef = input }} />
})