無法將 ReactJS 元件的屬性值傳遞給另一個元件
P粉647504283
P粉647504283 2023-08-16 00:30:36
0
1
571
<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>
P粉647504283
P粉647504283

全部回覆(1)
P粉420958692

試試這個導覽列:

import React, { useEffect, useState, useRef } from 'react';

const Navbar = ({ setHeight }) => {
  const refContainer = useRef();
  const [dimensions, setDimensions] = useState({ width: 0, height: 0 });

  useEffect(() => {
    const updateDimensions = () => {
      if (refContainer.current) {
        setDimensions({
          width: refContainer.current.offsetWidth,
          height: refContainer.current.offsetHeight,
        });
      }
    };

    updateDimensions();
    window.addEventListener('resize', updateDimensions);

    return () => {
      window.removeEventListener('resize', updateDimensions);
    };
  }, []);

  useEffect(() => {
    setHeight(dimensions.height);
  }, [dimensions.height, setHeight]);

  return <div ref={refContainer}>Navbar Content</div>;
};

export default Navbar;
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板