5

这是我的代码:

<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 中,这是可行的,它可以接受名称,但我不知道为什么不能打字?

4

1 回答 1

13

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
*/
于 2019-03-28T03:36:59.667 回答