Dav*_*ona 3 javascript typescript reactjs react-redux react-typescript
我使用 React 在 onSubmit 中发生以下事件,并将其从 Javascript 更改为 TypeScript。
const submitUserHandler = (e) => {
e.preventDefault();
dispatch(
authenticate({
name: e.target.personname.value,
pw: e.target.password.value,
})
);
};
Run Code Online (Sandbox Code Playgroud)
我尝试将 'e: React.ChangeEvent' 分配给该事件,但它提示如下错误:
类型“EventTarget & HTMLInputElement”上不存在属性“personname”。
我如何指定类型还包括用户名和密码?谢谢!
你可以做这样的事情
<form
ref={formRef}
onSubmit={(e: React.SyntheticEvent) => {
e.preventDefault();
const target = e.target as typeof e.target & {
personname: { value: string };
password: { value: string };
};
const email = target.personname.value; // typechecks!
const password = target.password.value; // typechecks!
// etc...
}}
>
<div>
<label>
Email:
<input type="personname" name="personname" />
</label>
</div>
<div>
<label>
Password:
<input type="password" name="password" />
</label>
</div>
<div>
<input type="submit" value="Log in" />
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
详情请参考
| 归档时间: |
|
| 查看次数: |
2891 次 |
| 最近记录: |