【发布时间】: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