在渲染组件后,将焦点设置在特定文本字段上的反应方式是什么?
文档似乎建议使用refs,例如:
ref="nameInput"
在渲染函数的输入字段中设置,然后调用:
this.refs.nameInput.getInputDOMNode().focus();
Run Code Online (Sandbox Code Playgroud)
但我应该在哪里打电话呢?我尝试了几个地方,但我无法让它工作.
我试图使用React refs在安装时聚焦Redux-Form字段.
当我尝试this.refs.title.getRenderedComponent().focus()
时componentDidMount
,会抛出一个错误:
edit_fund.js:77 Uncaught TypeError: Cannot read property 'getRenderedComponent' of undefined
当我在console.log this.refs中时,它主要是一个空对象,有时将'title'标识为ref,但它不可靠.
我错误地使用了refs吗?我的代码在下面供参考.
componentDidMount = () => {
this.refs.title
.getRenderedComponent()
.focus();
}
Run Code Online (Sandbox Code Playgroud)
...
<Field
id="title"
name="title"
component={FormInput}
type="text"
ref="title" withRef
/>
Run Code Online (Sandbox Code Playgroud) 我想实现一个自动对焦,我无法通过设置autofocus=true
而不是以编程方式从标记中找到方法.任何帮助?