无法将 ReactJS 组件的属性值传递给另一个组件
P粉647504283
2023-08-16 00:30:36
<p>如何在Home.js组件中获取Navbar.js组件中dimensions对象的最新更新值?我尝试将一个回调函数作为props从Home.js传递给Navbar.js(因为Home.js是Navbar.js的父组件),但我无法在Navbar.js中存储新更新的dimensions状态值。如果我将dimensions状态作为useEffect的依赖项传递,会导致无限循环。请帮助我。</p>
<pre class="brush:php;toolbar:false;">**Home.js组件**
const Home = () => {
const [heightNav, setHeightNav] = useState(0);
useEffect(() => {
console.log(heightNav);
}, [heightNav]);
return (
<div>
<Navbar
setHeight={(h) => {
setHeightNav(() => h);
}}
/>
</div>
);
};
**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 (
<Container ref={refContainer}>
</Container>
);
};</pre>
试一下这个导航栏: