【发布时间】:2021-10-26 20:30:05
【问题描述】:
假设我有 2 个组件,Parent 和 Child。我需要一种方法来访问Parents 在Child 中的宽度,并且还需要useEffect 在此宽度发生变化时触发一些代码。
当我在parent 上使用引用并将其作为道具传递给child 并尝试通过parentRef.current.clientWidth 访问它时,尝试使用useRef 给我一个类似于Cannot access clientWidth property of undefined 的错误.
片段
const parentRef = useRef();
return(
<Parent ref={parentRef}>
<Child parentRef={parentRef}/>
</Parent>
)
我该怎么办?
【问题讨论】:
-
你是如何传递 ref 的?
-
@e.a.添加在原始答案中。
-
对不起。我的意思是你如何在子组件中使用它。你在使用 forwardRef 吗?因为你不能像普通道具一样消耗它
-
@e.a.我将它用作普通道具。
forwardedRef是什么?你能给我举个例子吗? -
我在答案中发布了向您展示代码。它会解决你的问题
标签: html reactjs react-hooks