反应:如何使用钩子从子组件获取父组件的宽度?



假设我有两个组件,ParentChild。我需要一种在Child中访问Parents的宽度的方法,并且还需要useEffect在这个宽度改变时发射一些代码。

尝试使用useRef,当我在parent上使用引用时,会出现Cannot access clientWidth property of undefined的错误,并将其作为道具传递给child,并尝试通过parentRef.current.clientWidth访问它。

const parentRef = useRef();
return(
<Parent ref={parentRef}>
<Child parentRef={parentRef}/>
</Parent>
)

我该怎么办?

为了访问子组件中的ref,你需要在React中包装你的组件。转发函数&使用ref作为第二个参数&不在props对象内,所以:

const Child = React.forwardRef((props, ref) => {})

,在你的父母中,你会有:

<Child ref={parentRef}/>

你可以在这里阅读更多信息

让state在parentMake函数接受值并改变状态在props中将函数从父级传递给子级执行宽度值为

的子函数

您可以使用ResizeObserverapi来侦听附加在Parent上的resize事件

import { useEffect, useRef, useState } from "react";
const Child = ({ width = 0 }) => {
useEffect(() => {
// listen for the change in width
// do something here when the width changes
}, [width]);
return <p> Parent Div Size: {width} </p>;
};
const Parent = () => {
const divRef = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const resizeObserver = new ResizeObserver((entries) => {
// this callback gets executed whenever the size changes
// when size changes get the width and update the state
// so that the Child component can access the updated width
for (let entry of entries) {
if (entry.contentRect) {
setWidth(entry.contentRect.width);
}
}
});
// register the observer for the div
resizeObserver.observe(divRef.current);
// unregister the observer
return () => resizeObserver.unobserve(divRef.current);
}, []);
return (
<div
ref={divRef}
style={{
textAlign: "center",
height: "100px",
border: "solid 1px"
}}
>
<Child width={width} />
</div>
);
};
export default Parent;

工作沙箱

参考

调整观察者API大小

最新更新