[英]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
值?
筆記:
localRef
和parentRef
模式取自ReactJS 內部需要的 Optional forwardRef ,並且似乎是規范以這種方式發送的可選 ref 的一種不錯的方式。我最終使用了這個解決方案,因為我確定我只想支持普通的 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.