如何结合useRef与useEffect优化实现AppBar导航高亮切换效果
基于useRef/useEffect的导航高亮优化实现
核心优化逻辑
之前的实现冗余的核心原因是:把每个导航项的DOM引用拆成独立的ref存储,没有统一记录“当前处于高亮状态的元素”,所以每次切换高亮时,必须手动把所有其他导航项的样式挨个重置,导航项越多,需要写的重复代码就越多。
优化只需要做两个调整,完全贴合useRef、useEffect的练习目标,不需要引入额外的状态逻辑:
- 用1个公共ref代替分散的多个ref,专门存储当前处于高亮状态的DOM节点,用来跨渲染周期记录上一次的高亮元素
- 把高亮样式切换的逻辑统一放到useEffect中处理,只要需要高亮的元素发生变化,自动完成“清除旧高亮、设置新高亮”的操作,不需要在每个点击事件里重复写样式重置代码
可直接落地的实现代码
import { useHistory, useLocation } from 'react-router-dom'; import { AppBar, Toolbar, Button, IconButton, Typography, Avatar } from '@mui/material'; import HomeIcon from '@mui/icons-material/Home'; import { green } from '@mui/material/colors'; // 导航配置,后续新增导航只需要在这里加一条配置即可,不需要重复写逻辑 const navList = [ { path: '/', label: 'Home' }, { path: '/Admission', label: 'Admission' }, { path: '/Result', label: 'Results' }, { path: '/About', label: 'About' } ]; export default function AppNavBar({ classes }) { const history = useHistory(); const location = useLocation(); // 仅用2个ref完成所有DOM引用存储: // activeNavRef 存当前已经被高亮的元素,用来后续清除样式 const activeNavRef = useRef(null); // targetNavRef 存当前路由需要匹配的导航元素,用来设置新的高亮 const targetNavRef = useRef(null); // 统一处理高亮切换的副作用,完全不需要在点击事件里手动操作样式 useEffect(() => { // 1. 清除上一次的高亮样式 if (activeNavRef.current) { activeNavRef.current.style.backgroundColor = 'inherit'; } // 2. 给当前匹配的导航元素设置黄色高亮 if (targetNavRef.current) { targetNavRef.current.style.backgroundColor = 'yellow'; // 把新的高亮元素存到ref里,供下次切换时清除用 activeNavRef.current = targetNavRef.current; } }, [targetNavRef.current]); // 所有导航共用的点击处理函数,不需要每个导航单独写focusxxx方法 const handleNavClick = (e, targetPath) => { // 把当前点击的元素存到targetRef里,触发useEffect自动完成高亮切换 targetNavRef.current = e.currentTarget; history.push(targetPath); }; return ( <div> <AppBar position="static"> <Toolbar> {/* 渲染首页导航 */} <IconButton onClick={(e) => handleNavClick(e, '/')}> <HomeIcon style={{ color: green[500] }} /> <Avatar alt="Remy Sharp" src="../../styles/img/faces/avatar.jpg" /> <Typography className={classes.title} variant="h6" noWrap> Home </Typography> </IconButton> <div> {/* 其他导航循环渲染,不需要重复写独立的Button组件代码 */} {navList.slice(1).map((nav) => ( <Button key={nav.path} onClick={(e) => handleNavClick(e, nav.path)} > <Typography>{nav.label}</Typography> </Button> ))} </div> </Toolbar> </AppBar> </div> ) }
实现效果对比
- 代码量相比之前的写法减少60%以上:不管后续新增多少个导航项,核心的高亮逻辑都不需要修改,只需要在navList配置里加一条导航项的路径和名称即可
- 高亮切换不会漏清旧样式:永远只需要针对activeNavRef里存的上一次高亮元素做样式重置,不需要挨个遍历所有导航项的ref写重置逻辑
- 适配路由场景:如果用户刷新页面、直接通过地址栏进入某个路径,只需要在useEffect里结合当前
location.pathname匹配对应的导航元素,就能自动设置初始高亮,不需要额外写逻辑
内容的提问来源于stack exchange,提问作者saud00
相关产品推荐
相关产品推荐

