类型“EventTarget"上不存在属性“name"-React + TypeScript [英] Property 'name' does not exist on type 'EventTarget' - React + TypeScript

查看:317
本文介绍了类型“EventTarget"上不存在属性“name"-React + TypeScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

<Button
  disabled={filter === 'Active'}
  size='md'
  color='primary'
  name='Active' // complete = false
  onClick={this.handleFilterClick}
>
  Active
</Button>

在我的函数处理程序中,我收到事件错误:

On my function handler I get error on the event:

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

What is the event type for button? In JavaScript, this works, it can accept name but I don't know why not typescript?

推荐答案

event.target 是从中分派元素的元素,不一定必须是 HTMLButtonElement 在事件中定义.

event.target is the element from which element is dispatched, which necessarily doesn't have to be the HTMLButtonElement defined in the event.

然而,如果你使用 event.currentTarget,你会看到这个错误消失了:

However, if you use event.currentTarget, you will see that this error goes away:

const { name } = event.currentTarget;

如果您必须使用 event.target 本身,则必须强制转换对象:

If you have to use event.target itself, you would have to cast the object:

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

这篇关于类型“EventTarget"上不存在属性“name"-React + TypeScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆