簡體   English   中英

如何以類型安全的方式正確訪問 React 中 forwardRef 元素的 ref.current?

[英]How to correctly access in a type-safe way the ref.current of a forwardRef element in React?

這是類型安全問題的一個最小示例:

https://codesandbox.io/s/mystifying-dream-8v7kgu?file=/src/App.tsx

const CanvasContainer = forwardRef<HTMLCanvasElement>((props, parentRef) => {
  const localRef = useRef<HTMLCanvasElement>(null);
  const canvasRef = parentRef ?? localRef;

  useEffect(() => {
    // type-safety no longer works here, see code sandbox link
    console.log(canvasRef.current);
  }, []);

  return <canvas ref={canvasRef} />;
});

使用 typescript, canvasRef可以不僅僅是一個React.RefObject<HTMLCanvasElement> 為什么,以及如何在這種情況下實現類型安全並訪問.curent值?

筆記:

  • localRefparentRef模式取自ReactJS 內部需要的 Optional forwardRef ,並且似乎是規范以這種方式發送的可選 ref 的一種不錯的方式。
  • 這是一個孤立的案例,我想弄清楚如何支持這種代碼模式。 還有其他方法可以實現我在沒有 forwardRef 的情況下實現的功能。 我不是要求與我的畫布功能相關的解決方案,而是要澄清如何反應和反應的類型可以被馴服。

我最終使用了這個解決方案,因為我確定我只想支持普通的 refs 或根本不支持 refs 並且就像問題狀態的第一條評論(來自 Nikos)一樣,ref 也可以是一個 setter 函數。

const CanvasContainer = forwardRef<HTMLCanvasElement>((props, parentRef) => {
    if (typeof parentRef === "function") {
        throw new Error(
            `Only React Refs that are created with createRef or useRef are supported`
        )
    }

    const localRef = useRef<HTMLCanvasElement>(null)
    const canvasRef = parentRef ?? localRef
// ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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