这是我的代码:
<Button
disabled={filter === 'Active'}
size='md'
color='primary'
name='Active' // complete = false
onClick={this.handleFilterClick}
>
Active
</Button>
在函数处理程序上,我在事件上收到错误:
handleFilterClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
// continue here
const { name } = e.target;
它说:
Property 'name' does not exist on type 'EventTarget'.
我也尝试过:
(e: React.MouseEvent<HTMLInputElement, MouseEvent> & React.MouseEvent<HTMLButtonElement, MouseEvent>)
按钮的事件类型是什么?在javascript中,此方法有效,它可以接受名称,但我不知道为什么不输入打字稿?
答案 0 :(得分:1)
event.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
*/