我如何修复一个React TypeScript错误与useHotkeys钩子的返回值不匹配的div元素ref prop的



遵循React -hotkeys-hook包(https://react-hotkeys-hook.vercel.app/docs/documentation/useHotkeys/scoping-hotkeys)中的这些文档,我试图将一些热键的注册范围扩展到特定的React组件。然而,当我试图将这个包的'useHotkeys'钩子返回的ref对象通过它的ref prop传递给a时,会导致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

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

function useHotkeys<T extends Element>

,所以你可以修复这个错误通过正确的元素类型

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