在我的react ts应用程序中,我有以下代码:
useEffect(() => {
const handleEscKeyPress = (
event: React.KeyboardEvent<HTMLInputElement> & { isComposing: boolean }
) => {
if (event.isComposing || event.key === 'Escape') {
onClose();
return;
}
};
document.addEventListener('keydown', handleEscKeyPress);
return () => {
document.removeEventListener('keydown', handleEscKeyPress!);
};
}, []);
IDE突出显示文档。addEventListener('keydown',handleEscKeyPress);和消息:
const handleEscKeyPress: (event: React.KeyboardEvent<HTMLInputElement> & {
isComposing: boolean;
}) => void
No overload matches this call.
Overload 1 of 2, '(type: "keydown", listener: (this: Document, ev: KeyboardEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '(event: React.KeyboardEvent<HTMLInputElement> & { isComposing: boolean;}) => void' is not assignable to parameter of type '(this: Document, ev: KeyboardEvent) => any'.
Types of parameters 'event' and 'ev' are incompatible.
Type 'KeyboardEvent' is not assignable to type 'KeyboardEvent<HTMLInputElement> & { isComposing: boolean; }'.
Type 'KeyboardEvent' is missing the following properties from type 'KeyboardEvent<HTMLInputElement>': locale, nativeEvent, isDefaultPrevented, isPropagationStopped, persist
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '(event: React.KeyboardEvent<HTMLInputElement> & { isComposing: boolean;}) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(event: React.KeyboardEvent<HTMLInputElement> & { isComposing: boolean;}) => void' is not assignable to type 'EventListener'.
Types of parameters 'event' and 'evt' are incompatible.
Type 'Event' is not assignable to type 'KeyboardEvent<HTMLInputElement> & { isComposing: boolean; }'.
Type 'Event' is missing the following properties from type 'KeyboardEvent<HTMLInputElement>': altKey, charCode, ctrlKey, code, and 15 more.ts(2769)
应该为事件分配什么类型才能避免此问题?
2条答案
按热度按时间ifsvaxew1#
React键盘事件与直接来自浏览器的键盘事件不同。
document.addEventListener
不接受使用React事件的回调。您也不能指定事件在
HTMLInputElement
上-这不是keydown
事件可以触发的唯一元素。请仅使用KeyboardEvent
。因为
isComposing
已经是原生KeyboardEvent
上的一个类型化属性,所以可以完全不使用它。此外,由于函数将始终定义为:
非空Assert是多余:
czq61nw12#
常量句柄按键=(e:键盘事件&& {正在编写:布尔值})=〉{ //做一些事情};