在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
根据更新后的语法,你可以使用this.myRref.current.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
你不需要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'));
引用:@Dave对@Dhiraj的回答的评论;另一种方法是在被呈现的元素上使用ref属性的回调功能(在组件第一次呈现之后):
<input ref={ function(component){ React.findDOMNode(component).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]);
};
在尝试了上面的许多选项后,没有成功,我发现这是因为我禁用了输入,然后启用了输入,导致焦点丢失。
我有一个道具sendingAnswer将禁用输入,而我轮询后端。
<Input
autoFocus={question}
placeholder={
gettingQuestion ? 'Loading...' : 'Type your answer here...'
}
value={answer}
onChange={event => dispatch(updateAnswer(event.target.value))}
type="text"
autocomplete="off"
name="answer"
// disabled={sendingAnswer} <-- Causing focus to be lost.
/>
一旦我拆除了瘫痪的道具,一切又开始工作了。