【发布时间】: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
当我尝试强制类型时,代码会生成,但热键不起作用 - 代码如下:
const ref = useKeyboardFormSubmit(() => {
console.log('contact got keystrokes');
handleSubmit(onSubmit)();
}) as LegacyRef<HTMLDivElement>;
任何建议都非常感谢!
【问题讨论】:
标签: reactjs typescript react-hooks keyboard-events react-hook-form