我正在尝试获得一个函数来处理点击和键盘事件,因为我正在尝试使我的网络应用程序键盘可访问。当我对类型使用 |
符号时,出现错误:
Property 'key' does not exist on type 'KeyboardEvent<Element> | MouseEvent<Element, MouseEvent>'.
Property 'key' does not exist on type 'MouseEvent<Element, MouseEvent>'.
我目前的职能:
const handleChange = (e: React.KeyboardEvent | React.MouseEvent): void => {
if (e.type !== 'mousedown' || e.key !== ' ') return;
...other stuff...
}
有人可以指出正确的方向让我按预期工作吗?我可以只编写单独的函数,但我认为将它保留在一个函数中会很好。
最佳答案
您可以使用类型断言来执行此操作 (https://basarat.gitbook.io/typescript/type-system/type-assertion):
const handleChange = (e: React.KeyboardEvent | React.MouseEvent): void => {
if (e.type !== 'mousedown' || (e as React.KeyboardEvent).key !== ' ') return;
...other stuff...
}
关于javascript - 在一个函数中同时处理 React.KeyboardEvent 或 React.MouseEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65928720/