如何使用React引用来聚焦Redux表单字段? [英] How to use React refs to focus a Redux Form field?

查看:72
本文介绍了如何使用React引用来聚焦Redux表单字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用React refs在安装时聚焦Redux-Form字段。

I am trying to use React refs to focus a Redux-Form Field when it mounts.

当我在 this.refs.title.getRenderedComponent()。focus()时> componentDidMount ,抛出错误说:

When I try this.refs.title.getRenderedComponent().focus() in componentDidMount, an error is thrown saying:

edit_fund.js:77 Uncaught TypeError:无法读取属性'getRenderedComponent 'of undefined

当我在console.log this.refs时,它主要是一个空对象,有时将'title'标识为ref ,但它不可靠。

When I console.log this.refs, it is mostly an empty object and sometimes identifies 'title' as being a ref, but it is not dependable.

我错误地使用了参考号吗?我的代码在下面供参考。

Am I using refs incorrectly? My code is below for reference.

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

...

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


推荐答案

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

Please try setting ref using callback function:

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

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

and then use this to get underlying DOM node:

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

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

of if DOM input element is wrapped in another element:

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

根据React docs使用带有字符串的refs有一些问题。请查看 docs 了解更多详情。

According to React docs using refs with a string have some issues. Please check docs for more details.

这篇关于如何使用React引用来聚焦Redux表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆