属性“名称”在类型“ EventTarget”上不存在-React + TypeScript

时间:2019-03-28 02:46:48

标签: reactjs typescript react-tsx

这是我的代码:

<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中,此方法有效,它可以接受名称,但我不知道为什么不输入打字稿?

1 个答案:

答案 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
*/