admin管理员组文章数量:1424936
I have the following event in onSubmit using React and I am changing it from Javascript to TypeScript.
const submitUserHandler = (e) => {
e.preventDefault();
dispatch(
authenticate({
name: e.target.personname.value,
pw: e.target.password.value,
})
);
};
I have tried assigning 'e: React.ChangeEvent' to the event, but it prompts an error like this:
Property 'personname' does not exist on type 'EventTarget & HTMLInputElement'.
How could I specify the type also including personname and password? Thanks!
I have the following event in onSubmit using React and I am changing it from Javascript to TypeScript.
const submitUserHandler = (e) => {
e.preventDefault();
dispatch(
authenticate({
name: e.target.personname.value,
pw: e.target.password.value,
})
);
};
I have tried assigning 'e: React.ChangeEvent' to the event, but it prompts an error like this:
Property 'personname' does not exist on type 'EventTarget & HTMLInputElement'.
How could I specify the type also including personname and password? Thanks!
Share Improve this question edited Jan 23, 2021 at 15:25 DevLoverUmar 14.1k15 gold badges78 silver badges111 bronze badges asked Jan 23, 2021 at 15:13 David SolsonaDavid Solsona 431 silver badge5 bronze badges 2- 1 e.target will equal to your HTMLInput Element I believe. Need to see your HTML, why there is property of "personname" in the element – vdj4y Commented Jan 23, 2021 at 15:27
- typescript does not support inside event yet. You can use to pass this case: (e.target as any).personname.value – cuongdevjs Commented Jan 23, 2021 at 16:40
1 Answer
Reset to default 7You can do something like this
<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>
For details, reference
本文标签: javascriptType of an event in TypeScript in ReactStack Overflow
版权声明:本文标题:javascript - Type of an event in TypeScript in React - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745414467a2657616.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论