首页 > 解决方案 > 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')”的错误

标签: javascriptreactjsreact-nativeinputfocus

解决方案


您需要在调用 focus() 之前确保“this.emailRef.current”存在,因为有时创建引用需要时间。尝试添加延迟作为解决方法,例如:

componentDidMount = () => {
  setTimeout(() => {
    if (this.emailRef.current) {
      this.emailRef.current.focus();
    }
  }, 500);
}

推荐阅读