Heim > Fragen und Antworten > Hauptteil
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;