簡體   English   中英

如何使用 React 和 TypeScript 鍵入用於任意元素的 ref?

[英]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 )和
  • 將由 React 控制(您打算將其傳遞給 JSX 元素的ref屬性)

RefObject<T> 引用定義useRef的類型聲明文件

function useRef<T>(initialValue: T|null): RefObject<T>;

以下是如何編寫一個返回這樣的 ref 的鈎子:

TS游樂場

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM