reactjs - 无法在 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'
解决方案
它是一个类型错误,请尝试:
emailEl= createRef<HTMLInputElement | null>();
// or
emailEl= createRef<HTMLInputElement>(null);
registerUser = () => {
if (emailEl && emailEl.current) {
// ts knows value not null
this.emailEl.current.value;
}
}
推荐阅读
- sql - 在 SQL 中选择除某些 Data_Type(例如图像)之外的所有列
- javascript - 在 Mapview Marker 标题上反应原生 onPress 事件?
- c++ - Win32 API 打开新窗口
- join - Lead Lag 函数在 Teradata 15.0 上不起作用。任何可以给我类似结果的替代方法
- python - 无法卸载Tensorflow 2.1.0 因为conda 找不到包和解决环境失败
- r - py_call_impl(callable, dots$args, dots$keywords) 中的错误:ValueError:在用户代码中:
- database - MongoDb 根据动态键获取记录
- javascript - 没有错误显示,但 Chrome.Storage.Sync。Get 没有收到我在 Chrome.Storage.Sync.Set 中设置的内容
- java - Spring RestController 返回错误的内容类型
- r - 将数据框列中的值重新编码为 R 中的缺失值