在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
没有自动对焦的简单解决方案:
<input ref={ref => ref && ref.focus()}
onFocus={(e)=>e.currentTarget.setSelectionRange(e.currentTarget.value.length, e.currentTarget.value.length)}
/>
ref触发focus,然后触发onFocus计算结束并相应地设置游标。
其他回答
这一点对我很有用:
<input autoFocus={true} />
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>
);
};
ReactDOMComponent:不要访问DOM节点的.getDOMNode();相反,直接使用节点。这个DOM节点由App渲染。
应该是
componentDidMount: function () {
this.refs.nameInput.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>
);
}
重点关注功能组件使用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