![](/img/trans.png)
[英]How do I type a ref callback with useCallback (with Typescript)?
[英]How do I type a ref that is used on arbitrary elements with React and TypeScript?
我有一个 React Hook,可用于任意元素(任何扩展HTMLElement
的元素)来检测元素是否悬停。 尝试键入用法时,我无法满足 TypeScript 编译器的要求。 这是一个简单的复制:
function useHover<T extends HTMLElement>(): [MutableRefObject<T>] {
const ref = useRef<T | null>(null);
return [ref];
}
const App = () => {
const [ref] = useHover<HTMLButtonElement | HTMLAnchorElement>();
const Element = Math.random() > 0.5 ? 'a' : 'button';
return <Element ref={ref}>{`tag: ${Element}`}</Element>;
};
在 Hook 中,我不知道将使用什么元素类型,因此我使用了带有extends HTMLElement
约束的泛型。 然而,在 React 组件中,我确实知道 ref 将使用的元素类型的有限子集。
使用上面的代码,我得到这种类型的错误:
Type 'MutableRefObject<HTMLButtonElement | HTMLAnchorElement>' is not assignable to type 'LegacyRef<HTMLAnchorElement> & LegacyRef<HTMLButtonElement>'.
Type 'MutableRefObject<HTMLButtonElement | HTMLAnchorElement>' is not assignable to type 'RefObject<HTMLAnchorElement> & RefObject<HTMLButtonElement>'.
Type 'MutableRefObject<HTMLButtonElement | HTMLAnchorElement>' is not assignable to type 'RefObject<HTMLAnchorElement>'.
Types of property 'current' are incompatible.
Type 'HTMLButtonElement | HTMLAnchorElement' is not assignable to type 'HTMLAnchorElement'.
Type 'HTMLButtonElement' is missing the following properties from type 'HTMLAnchorElement': charset, coords, download, hreflang, and 19 more.
键入此 Hook 和组件的正确方法是什么,以便我可以在扩展HTMLElement
的任何元素上使用 Hook?
键入ref
的正确方法
T extends HTMLElement
)和ref
属性) 是RefObject<T>
。 引用定义useRef
的类型声明文件:
function useRef<T>(initialValue: T|null): RefObject<T>;
以下是如何编写一个返回这样的 ref 的钩子:
import {type RefObject, useRef} from 'react';
function useElementRef <T extends HTMLElement>(): RefObject<T> {
const ref = useRef<T>(null);
return ref;
}
但是,您不需要将ref
用于“useHover”钩子(确定元素是否被指针悬停)。 请参阅我的其他答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.