【问题标题】:How do I fix a React TypeScript error with the return value of useHotkeys hook not matching the type of the div element ref prop如何使用 useHotkeys hook 的返回值与 div element ref prop 的类型不匹配来修复 React TypeScript 错误
【发布时间】:2021-10-11 22:58:13
【问题描述】:

根据 react-hotkeys-hook 包 (https://react-hotkeys-hook.vercel.app/docs/documentation/useHotkeys/scoping-hotkeys) 中的这些文档,我正在尝试将一些热键的注册范围限定为特定的 React 组件。但是,当我尝试通过它的 ref 属性将它传递给 a 时,这个包的 'useHotkeys' 钩子返回的 ref 对象会导致 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 |未定义'。

当我尝试强制类型时,代码会生成,但热键不起作用 - 代码如下:

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

任何建议都非常感谢!

【问题讨论】:

    标签: reactjs typescript react-hooks keyboard-events react-hook-form


    【解决方案1】:

    阅读文档,您可以看到 useHotkeys 接受泛型。

    function useHotkeys<T extends Element>
    

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

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

    【讨论】:

    • 这也可以使其构建,但仍未触发回调。 tabIndex 道具正在渲染。
    • @Byofuel 你能创建一个最小的 repo 来重现错误吗?
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2019-03-02
    • 1970-01-01
    相关资源
    最近更新 更多