搜尋

首頁  >  問答  >  主體

無法將 ReactJS 元件的屬性值傳遞給另一個元件

<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粉647504283P粉647504283466 天前545

全部回覆(1)我來回復

  • P粉420958692

    P粉4209586922023-08-16 22:15:16

    試試這個導覽列:

    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;

    回覆
    0
  • 取消回覆