为什么 typescript 不接受React.KeyboardEvent< HTMLInputElement>?

sycxhyv7  于 2022-12-27  发布在  TypeScript
关注(0)|答案(2)|浏览(223)

在我的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)

应该为事件分配什么类型才能避免此问题?

ifsvaxew

ifsvaxew1#

React键盘事件与直接来自浏览器的键盘事件不同。document.addEventListener不接受使用React事件的回调。
您也不能指定事件在HTMLInputElement上-这不是keydown事件可以触发的唯一元素。请仅使用KeyboardEvent
因为isComposing已经是原生KeyboardEvent上的一个类型化属性,所以可以完全不使用它。

const handleEscKeyPress = (
    event: KeyboardEvent
) => {

此外,由于函数将始终定义为:

document.removeEventListener('keydown', handleEscKeyPress!);

非空Assert是多余:

document.removeEventListener('keydown', handleEscKeyPress);
czq61nw1

czq61nw12#

import { KeyboardEvent } from 'react';

常量句柄按键=(e:键盘事件&& {正在编写:布尔值})=〉{ //做一些事情};

相关问题