在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
在组件渲染后,react如何设置聚焦在特定文本字段上?
文档似乎建议使用参考,例如:
在渲染函数的输入字段上设置ref="nameInput",然后调用:
this.refs.nameInput.getInputDOMNode().focus();
但是我该把它叫什么呢?我在几个地方试过了,但都不行。
当前回答
这是正确的方法,如何自动对焦。当你使用callback而不是string作为ref value时,它会被自动调用。你得到了你的ref,而不需要使用getDOMNode触摸DOM
render: function() {
return <TextInput ref={(c) => this._input = c} />;
},
componentDidMount: function() {
this._input.focus();
},
其他回答
根据更新后的语法,你可以使用this.myRref.current.focus()
阅读几乎所有的答案,但没有看到getRenderedComponent().props.input
设置文本输入参考
this.refs.username.getRenderedComponent () .props.input.onChange(”);
<input type="text" autoFocus />
总是先尝试简单和基本的解决方案,对我来说很有效。
@Dhiraj的答案是正确的,为了方便,你可以使用自动对焦道具在安装时自动对焦:
<input autoFocus name=...
注意,在jsx中,它是自动聚焦(大写F),不像普通的旧html是不区分大小写的。
你不需要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'));