Reactjs 财产';名称';不存在于类型';事件目标';-反应+;打字稿
这是我的代码:Reactjs 财产';名称';不存在于类型';事件目标';-反应+;打字稿,reactjs,typescript,react-tsx,Reactjs,Typescript,React Tsx,这是我的代码: <Button disabled={filter === 'Active'} size='md' color='primary' name='Active' // complete = false onClick={this.handleFilterClick} > Active </Button> 我还尝试: (e: React.MouseEvent<HTMLInputElement, MouseEvent> &a
<Button
disabled={filter === 'Active'}
size='md'
color='primary'
name='Active' // complete = false
onClick={this.handleFilterClick}
>
Active
</Button>
我还尝试:
(e: React.MouseEvent<HTMLInputElement, MouseEvent> & React.MouseEvent<HTMLButtonElement, MouseEvent>)
(e:React.MouseEvent&React.MouseEvent)
按钮的事件类型是什么?在JavaScript中,它可以接受name,但我不知道为什么不能使用typescript?
事件。target
是从中调度元素的元素,它不一定是事件中定义的HTMLButtonElement
但是,如果使用event.currentTarget
,您将看到此错误消失:
const { name } = event.currentTarget;
如果必须使用event.target
本身,则必须强制转换对象:
const { name } = event.target as HTMLButtonElement;
从打字中:
/**
* currentTarget - a reference to the element on which the event listener is registered.
*
* target - a reference to the element from which the event was originally dispatched.
* This might be a child element to the element on which the event listener is registered.
* If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
*/
同意使用currentTarget。您还可以优化event.target而不是强制转换
如果(e.target instanceof HTMLButtonElement){e.target.name;}
@TLadd true,那将是更好的方法
const { name } = event.target as HTMLButtonElement;
/**
* currentTarget - a reference to the element on which the event listener is registered.
*
* target - a reference to the element from which the event was originally dispatched.
* This might be a child element to the element on which the event listener is registered.
* If you thought this should be `EventTarget & T`, see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/12239
*/