无法将 ReactJS 组件的属性值传递给另一个组件
P粉647504283
P粉647504283 2023-08-16 00:30:36
0
1
446

如何在Home.js组件中获取Navbar.js组件中dimensions对象的最新更新值?我尝试将一个回调函数作为props从Home.js传递给Navbar.js(因为Home.js是Navbar.js的父组件),但我无法在Navbar.js中存储新更新的dimensions状态值。如果我将dimensions状态作为useEffect的依赖项传递,会导致无限循环。请帮助我。

**Home.js组件** const Home = () => { const [heightNav, setHeightNav] = useState(0); useEffect(() => { console.log(heightNav); }, [heightNav]); return ( 
{ setHeightNav(() => h); }} />
); }; **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 ( ); };
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 
Navbar Content
; }; export default Navbar;
    最新下载
    更多>
    网站特效
    网站源码
    网站素材
    前端模板
    关于我们 免责声明 Sitemap
    PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!