![](/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.