首页 > 解决方案 > 无法在 reactJS Typescript 中获取输入值

问题描述

我是 Typescript 的新手,在尝试 console.log 输入字段值时遇到错误。有什么建议么?代码 :

类注册扩展 Component<{},userState> {

state = {
    userList : []
}

emailEl= createRef<HTMLInputElement>()
passwordEl= createRef<HTMLInputElement>()
confirmpasswordEl= createRef<HTMLInputElement>()

registerUser = () => {
    const {userList} = this.state
    const destructList = [...userList]
    // const newUser = [destructList, {
    //     email:this.emailEl.current.value,
    //     password:this.passwordEl.current.value
    //
    // }]
    console.log('--------destructList', this.emailEl.current);

}



render() {
    return (
        <div className="container">
            <h1 className={'registerH1'}>Registration</h1>
            <div className="email">
                <input ref={this.emailEl}  type={'email'} placeholder={'Enter your E-mail'} />
            </div>
            <div ref={this.passwordEl} className="password">
                <input type={'password'} placeholder={'Enter your password'} />
            </div>
            <div ref={this.confirmpasswordEl} className="confirmPassword">
                <input type={'password'} placeholder={'Confirm your password'} />
            </div>
            <div id={'buttons'} className="buttons">
                <Link to={'/login'} >
                    <button>Log In</button>
                </Link>
                <button  onClick={() => this.registerUser()}>Registration</button>
            </div>
        </div>
    )
}

这是错误:

TS2531: Object is possibly 'null'

标签: reactjstypescript

解决方案


它是一个类型错误,请尝试:

emailEl= createRef<HTMLInputElement | null>();

// or
emailEl= createRef<HTMLInputElement>(null);
registerUser = () => {
    if (emailEl && emailEl.current) {
       // ts knows value not null
       this.emailEl.current.value;
    }
}

查看文档React.createRef


推荐阅读