如何在Home.js组件中获取Navbar.js组件中dimensions对象的最新更新值?我尝试将一个回调函数作为props从Home.js传递给Navbar.js(因为Home.js是Navbar.js的父组件),但我无法在Navbar.js中存储新更新的dimensions状态值。如果我将dimensions状态作为useEffect的依赖项传递,会导致无限循环。请帮助我。
**Home.js组件** const Home = () => { const [heightNav, setHeightNav] = useState(0); useEffect(() => { console.log(heightNav); }, [heightNav]); return (); }; **Navbar.js组件** const Navbar = ({ setHeight }) => { const refContainer = useRef(); const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); useEffect(() => { if (refContainer.current) { setDimensions(() => { return { width: refContainer.current.offsetWidth, height: refContainer.current.offsetHeight, }; }); setHeight(dimensions.height); } }, []); return ({ setHeightNav(() => h); }} /> ); };
试一下这个导航栏: