gpb*_*lio 5 typescript reactjs react-tsx
这是我的代码:
<Button
disabled={filter === 'Active'}
size='md'
color='primary'
name='Active' // complete = false
onClick={this.handleFilterClick}
>
Active
</Button>
Run Code Online (Sandbox Code Playgroud)
在我的函数处理程序上,我收到事件错误:
handleFilterClick = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
// continue here
const { name } = e.target;
Run Code Online (Sandbox Code Playgroud)
它说:
Property 'name' does not exist on type 'EventTarget'.
Run Code Online (Sandbox Code Playgroud)
我也试过:
(e: React.MouseEvent<HTMLInputElement, MouseEvent> & React.MouseEvent<HTMLButtonElement, MouseEvent>)
Run Code Online (Sandbox Code Playgroud)
按钮的事件类型是什么?在 JavaScript 中,这有效,它可以接受名称,但我不知道为什么不打字稿?
event.target是从中分派元素的元素,不一定必须是HTMLButtonElement事件中定义的元素。
但是,如果您使用event.currentTarget,您将看到此错误消失:
const { name } = event.currentTarget;
Run Code Online (Sandbox Code Playgroud)
如果必须使用event.target自身,则必须强制转换对象:
const { name } = event.target as HTMLButtonElement;
Run Code Online (Sandbox Code Playgroud)
从打字:
/**
* 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
*/
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3889 次 |
| 最近记录: |