【问题标题】:Trying to use React.createRef() but getting error: TypeError: Cannot read property 'focus' of null尝试使用 React.createRef() 但出现错误:TypeError: Cannot read property 'focus' of null
【发布时间】:2020-03-30 17:23:31
【问题描述】:

文件中的代码是:

import React, { Component } from 'react'

class LoginModal extends Component {

    constructor(props) {
        super(props)
        this.mobileInput = React.createRef();    // <------------CREATED REF Here
    }

   componentDidMount() {
        this.mobileInput.current.focus()        // <<<------------Getting ERROR here
   }

render() {
        return (
          <input
            type='number'
            onChange={this.handleInputChange('mobile')}
            className='form-control'
            placeholder='Enter mobile'
            name='mobile'
            ref={this.mobileInput}           // <<<------------added ref to input
         />
       )
    }

我得到的错误是:

TypeError:无法读取 null 的属性“焦点”

我尝试过的:

  • 我尝试使用自动对焦道具,但在我当前的项目设置中似乎不起作用。
  • 尝试使用 componentDidUpdate 而不是 componentDidMount。

*文件中有更多代码。为了清楚起见,我删除了不必要的代码。

【问题讨论】:

  • 您的代码运行良好,能否发布完整代码?
  • @ChrisG 为什么你会在没有任何证据证明它有效的情况下这么说?
  • 这能回答你的问题吗? Set focus on input after render
  • @AnuragSrivastava 你的意思是像codesandbox 这样的证据,我在发表评论之前设置了? ??????
  • @ChrisG 是的 :)

标签: javascript reactjs focus autofocus


【解决方案1】:

我找到了答案。只需要使用这个。

<input ref={input => input && input.focus()}/>

【讨论】:

    猜你喜欢
    • 2020-09-05
    • 1970-01-01
    • 2018-04-01
    • 2016-10-03
    • 2016-10-28
    • 1970-01-01
    • 2019-10-26
    • 2021-08-12
    • 2018-06-30
    相关资源
    最近更新 更多