無法將 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>
試試這個導覽列: