[英]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.