javascript - TypeError:null 不是对象(评估'_this2.emailRef.current.focus - 如何在打开屏幕时自动聚焦输入字段
问题描述
class Signin
constructor(props) {
super(props);
this.emailRef = React.createRef();
this.passwordRef = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
this.login = this.login.bind(this);
}
focusTextInput=()=>{
this.passwordRef.current.focus()
}
componentDidMount=()=> {
// this.refs.emailRef.focus()
this.emailRef.current.focus();
// this.focusTextInput();
}
render(){
return (
<SafeAreaView>
<Input
ref={this.emailRef}
/>
</SafeAreaView>
);
}
这会导致类似“TypeError: null is not an object (evalating '_this2.emailRef.current.focus')”的错误
解决方案
您需要在调用 focus() 之前确保“this.emailRef.current”存在,因为有时创建引用需要时间。尝试添加延迟作为解决方法,例如:
componentDidMount = () => {
setTimeout(() => {
if (this.emailRef.current) {
this.emailRef.current.focus();
}
}, 500);
}
推荐阅读
- python - django 2.2 上不存在 ContentType 匹配查询
- typescript - useStaticQuery:无效的挂钩调用。Hooks 只能在函数组件的主体内部调用
- lua - 我可以使用 os.date 将秒转换为时间格式吗?
- python - 使用 Kivy 安装并运行额外的 APK 文件
- javascript - 当有明确的值时,为什么这些数据显示未定义?
- jquery - 如何在循环中实现多个jquery formBuilder?
- svn - 从工作副本重建本地 SVN 存储库
- react-native - iOS 的分发代码签名 Mapbox.framework 失败
- r - 我应该如何解释 R 中函数 multinom 的结果?
- ruby - 什么决定了 Ruby 中整数的长度?