gpt4 book ai didi

reactjs - 类型 'name' 上不存在属性 'EventTarget' - React + TypeScript

转载 作者:行者123 更新时间:2023-12-04 01:11:26 30 4
gpt4 key购买 nike

这是我的代码:

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

最佳答案

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

关于reactjs - 类型 'name' 上不存在属性 'EventTarget' - React + TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55389447/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com