尝试使用 React.createRef() 但出现错误:类型错误:无法读取 null 的属性"焦点"



文件中的代码为:

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的属性"focus">

我试过的:

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

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

我找到了答案。只要用这个就行了
<input ref={input => input && input.focus()}/>

相关内容

最新更新