小编典典

如何使用React refs聚焦Redux Form字段?

reactjs

我正在尝试使用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,但它不是可靠的。

我是否正确使用了引用?我的代码在下面供参考。

componentDidMount = () => {
  this.refs.title
  .getRenderedComponent()
  .focus();
}

 <Field
    id="title"
    name="title"
    component={FormInput}
    type="text"
    ref="title" withRef
 />

阅读 297

收藏
2020-07-22

共1个答案

小编典典

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

ref={(input) => { this.title = input; }}

然后使用它来获取基础的DOM节点:

ReactDOM.findDOMNode(this.title).focus();

DOM输入元素是否包装在另一个元素中:

ReactDOM.findDOMNode(this.title).getElementsByTagName("input")[0].focus()

根据React文档,使用带字符串的refs存在一些问题。请检查文档以获取更多详细信息。

2020-07-22