如何使用React引用来聚焦Redux表单字段?

Tre*_*son 7 javascript reactjs redux-form react-redux-form

我试图使用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)

Bar*_*icz 7

请尝试使用回调函数设置ref:

ref={(input) => { this.title = input; }}
Run Code Online (Sandbox Code Playgroud)

然后使用它来获取底层DOM节点:

ReactDOM.findDOMNode(this.title).focus();
Run Code Online (Sandbox Code Playgroud)

如果DOM输入元素包含在另一个元素中:

ReactDOM.findDOMNode(this.title).getElementsByTagName("input")[0].focus()
Run Code Online (Sandbox Code Playgroud)

根据React docs使用带有字符串的refs有一些问题.请查看文档以获取更多详细信息.