React JS如何实现Navbar组件首次渲染背景透明、滚动后变白

问题原因
- 状态初始值不符合需求:代码中
changeColor = true对应导航栏透明样式,但是初始状态赋值为false,首次加载自然显示白色背景 - 缺少初始位置判断逻辑:滚动监听函数只有在页面滚动时才会触发,页面首次加载时没有触发滚动动作,不会执行位置判断逻辑
- useEffect使用错误:依赖数组添加了
changeColor,会导致每次状态更新都重复注册滚动监听事件,没有对应移除逻辑会造成内存泄漏
修复后的完整代码
import React,{useState,useEffect} from 'react'; import {Link} from 'react-router-dom'; import {motion} from 'framer-motion'; const showNavVariant = { hidden: { y:-500 }, visible: { y:0, transition: { type:'spring', stiffness:30 } } } const Navbar = () => { // 初始值改为true,默认顶部透明 const [changeColor,setChangeColor] = useState(true); useEffect(() => { // 抽离判断函数,方便首次加载和滚动时复用 const handleScroll = () => { if(window.scrollY === 0) { setChangeColor(true); } else { setChangeColor(false); } } // 首次加载主动执行一次,判断当前页面位置 handleScroll(); // 注册滚动监听 window.addEventListener('scroll', handleScroll); // 清理函数,组件卸载时移除监听避免内存泄漏 return () => window.removeEventListener('scroll', handleScroll); },[]) // 依赖改为空数组,只执行一次注册逻辑 return ( <motion.nav className={changeColor ? 'flex justify-center bg-transparent w-full shadow-xl fixed text-gray-100 z-50' : 'flex justify-center bg-gray-100 h-16 opacity-90 w-full shadow-xl fixed z-50' } variants={showNavVariant} initial="hidden" animate="visible" > <div className="max-w-7xl w-full flex justify-between items-center px-5"> <div className={changeColor ? "border-2 border-gray-100 text-gray-100 rounded p-5 m-2 ml-20" : "border-2 border-gray-800 rounded p-3 m-2 ml-20 text-gray-700"}> <h1 className="font-bold">Milktea</h1> </div> <div className={changeColor ? "grid grid-rows-2" : "grid grid-rows-1"}> <div className={changeColor ? 'flex justify-end px-20 py-4' : 'px-20 py-4 hidden'}> <div className="flex px-10"> <svg className="w-6 h-6 text-gray-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"> <path d="M2.003 5.884L10 9.882l7.997-3.998A2 2 0 0016 4H4a2 2 0 00-1.997 1.884z" /><path d="M18 8.118l-8 4-8-4V14a2 2 0 002 2h12a2 2 0 002-2V8.118z" /> </svg> <p className="text-yellow-500 ml-3 cursor-pointer">milkteashop@gmail.com</p> </div> <div className="grid grid-cols-2 gap-5 justify-items-center self-center text-gray-400"> <Link to="#" className="fa fa-facebook"></Link> <Link to="#" className="fa fa-instagram"></Link> </div> </div> <ul className="grid grid-cols-5 justify-items-center gap-5 px-10"> <Link className="navBtn" to="/"> <li>Home</li> </Link> <Link className="navBtn" to="/products"> <li>Products</li> </Link> <Link className="navBtn" to="/locations"> <li>Locations</li> </Link> <Link className="navBtn" to="/franchise"> <li>Franchise</li> </Link> <Link className="navBtn" to="#contact-us"> <li>Contact Us</li> </Link> </ul> </div> </div> </motion.nav> ) } export default Navbar
内容的提问来源于stack exchange,提问作者Paul Andres
相关产品推荐
相关产品推荐

