admin管理员组文章数量:1387360
I'm making a React + typescript project. And i have number button which looks like this:
<button className="num" type='button' value={'1'} onClick={inputHandler}>1</button>
You can notice that i also have onClick={inputHandler} on that button:
const inputHandler = (event: any) => {
event.preventDefault();
setInput(prev => prev.replace('_', event.target.value));}
This handler taking a value prop of button and setting it in to the input. So i am stucked on typing event for this handler. Every type i am defining returns:
Property 'value' does not exist on type 'EventTarget'.
If i typing it as "any", obviously it working. But i need to define exact type for it. Help me please.
I'm making a React + typescript project. And i have number button which looks like this:
<button className="num" type='button' value={'1'} onClick={inputHandler}>1</button>
You can notice that i also have onClick={inputHandler} on that button:
const inputHandler = (event: any) => {
event.preventDefault();
setInput(prev => prev.replace('_', event.target.value));}
This handler taking a value prop of button and setting it in to the input. So i am stucked on typing event for this handler. Every type i am defining returns:
Property 'value' does not exist on type 'EventTarget'.
If i typing it as "any", obviously it working. But i need to define exact type for it. Help me please.
Share Improve this question asked Jan 29, 2022 at 15:58 ТимурТимур 252 silver badges5 bronze badges2 Answers
Reset to default 3Usually I'll type the event argument as a generic Event.
Inside the function I'll make a variable that receives the actual HTML element and then cast the type using the as
keyword, because the argument "event" itself is not a HTML element, it is more advisable to make a variable with the target.
const inputHandler = (event: Event) => {
event.preventDefault();
const element = event.target as HTMLButtonElement;
setInput(prev => prev.replace('_', element.value));
}
You can use event: React.MouseEvent<HTMLButtonElement, MouseEvent>
as type, like so:
const inputHandler = (
event: React.MouseEvent<HTMLButtonElement, MouseEvent>
) => {
event.preventDefault();
//...
};
本文标签: javascriptReact typescript onClick event typingStack Overflow
版权声明:本文标题:javascript - React typescript onClick event typing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744489556a2608653.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论