ReactJS:使用React Pro Sidebar时无法为菜单项设置Active激活类
React Pro Sidebar 的 <MenuItem> 组件原生支持 active 布尔属性,你只需要将当前页面路由和菜单项对应的路由做匹配,给命中的菜单项的 active 属性赋值为 true 即可。
如果你用的是 react-router 作为路由方案,实现逻辑如下:
完整代码示例
import { useLocation } from 'react-router-dom'; import { SidebarContent, Menu, MenuItem } from 'react-pro-sidebar'; import { IoHomeOutline, IoPeopleOutline, IoCellularOutline } from 'react-icons/io5'; import { Link } from 'react-router-dom'; const Sidebar = () => { // 获取当前页面路由 const { pathname } = useLocation(); return ( <SidebarContent> <Menu iconShape="square"> <MenuItem icon={<IoHomeOutline />} active={pathname === '/home'} > Home <Link to="/home" /> </MenuItem> <MenuItem icon={<IoPeopleOutline />} active={pathname === '/oncalls'} > HighSev OnCalls <Link to="/oncalls" /> </MenuItem> <MenuItem icon={<IoCellularOutline />} active={pathname === '/reports'} > Reports <Link to="/reports" /> </MenuItem> </Menu> </SidebarContent> ); }; export default Sidebar;
样式自定义说明
组件默认会给active为true的菜单项添加高亮样式,如果你需要自定义激活样式,可以直接覆盖组件默认类名:
/* 示例:自定义激活态背景和文字颜色 */ .ps-menu-button.ps-active { background-color: #e6f7ff; color: #1890ff; }
如果你有嵌套路由场景(比如/reports/detail、/reports/list都要激活Reports菜单项),可以把判断逻辑改成
active={pathname.startsWith('/reports')}即可。
内容的提问来源于stack exchange,提问作者yush
相关产品推荐
相关产品推荐

