网站搜索

reactjs - 如何修复 React TypeScript 错误:useHotkeys 钩子的返回值与 div 元素 ref 属性的类型不匹配


按照 react-hotkeys-hook 包的这些文档(https://react-hotkeys-hook.vercel.app/docs/documentation/useHotkeys/scoping-hotkeys),我正在尝试将一些快捷键的注册限定在特定的 React 组件中。然而,当我尝试通过 ref 属性将该包的 useHotkeys 钩子返回的 ref 对象传给 <div> 时,会导致 TypeScript 错误。(当我不将快捷键限定在特定组件时,它可以正常工作,但这个错误阻止了代码的构建。)

我的钩子代码:

import { useHotkeys, Options } from 'react-hotkeys-hook';

export const useKeyboardFormSubmit = (
  callback: () => void,
  deps: any[] = [],
) => {
  const hotKeyOptions: Options = {
    enableOnTags: ['INPUT', 'TEXTAREA', 'SELECT'],
  };
  const ref = useHotkeys(
    'ctrl+enter, cmd+enter',
    () => {
      callback();
    },
    hotKeyOptions,
    deps,
  );
  return ref;
};

React 函数组件的摘录:

const EditAccountForm: FC<EditAccountFormProps> = (props) => {
  ...........
  const ref = useKeyboardFormSubmit(() => {
    console.log('contact got keystrokes');
    handleSubmit(onSubmit)();
  });
  ...........
  return (<div ref={ref} tabIndex={-1}>X</div>)

这会产生这个构建错误:

TypeScript error in /Users/byofuel/code/monetize-now/platform/frontend/src/routes/Accounts/EditAccountForm.tsx(139,12):
Type 'MutableRefObject<Element | null>' is not assignable to type 'LegacyRef<HTMLDivElement> | undefined'.
  Type 'MutableRefObject<Element | null>' is not assignable to type 'RefObject<HTMLDivElement>'.
    Types of property 'current' are incompatible.
      Type 'Element | null' is not assignable to type 'HTMLDivElement | null'.
        Type 'Element' is missing the following properties from type 'HTMLDivElement': align, accessKey, accessKeyLabel, autocapitalize, and 108 more.  TS2322

    137 |       )}
    138 |     >
  > 139 |       <div ref={ref}>X</div>
        |            ^

看起来 useHotKeys 返回一个 'MutableRefObject',但是对于 div 元素的 ref 属性,React 期望的是 'LegacyRef | undefined'。

当我尝试强制类型时,代码可以编译,但是快捷键不起作用 —— 代码如下:

const ref = useKeyboardFormSubmit(() => {
    console.log('contact got keystrokes');
    handleSubmit(onSubmit)();
  }) as LegacyRef<HTMLDivElement>;

任何建议都将不胜感激!

答案#1

阅读文档你可以看到 useHotkeys 接受一个泛型。

function useHotkeys<T extends Element>

因此您可以通过传递正确的元素类型来修复此错误

const ref = useHotkeys<HTMLDivElement>(...)