无法将 ReactJS 组件的属性值传递给另一个组件
P粉647504283
P粉647504283 2023-08-16 00:30:36
0
1
568
<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;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板