You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Router侧边栏如何为当前激活的导航项添加active类

问题原因&解决方案

你遇到的问题由3个错误共同导致,按顺序修改即可:

  1. 组件使用错误
    activeClassName是NavLink组件的专属属性,你代码中使用的Link组件不会识别该属性,无法自动添加激活类。
  2. CSS Modules类名引用错误
    你使用了CSS Modules(类名通过style.xxx引入),直接写activeClassName="active"会添加全局类,而非你样式文件中的局部类,需要改为activeClassName={style.active}。
    注意:如果你使用的是react-router-dom v6版本,activeClassName属性已被移除,需要通过className回调函数设置激活类:
    className={({isActive}) => isActive ? style.active : ''}
  3. 缺少激活状态样式规则
    你当前样式表只配置了hover状态的样式,没有对应激活类的样式规则,需要新增对应的样式。如果需要兼容不支持:has选择器的浏览器,推荐直接调整结构,通过NavLink的isActive状态给导航项加类,修改后完整代码如下:

修改后组件代码

import { NavLink } from 'react-router-dom'

const Sidebar = () => {
    return (
        <div className={style.sidebarContainer} >
            <NavLink to='/' className={({isActive}) => 
                `${style.navItem} ${isActive ? style.active : ''}`
            }>
                  <PersonIcon />
            </NavLink>
            <NavLink to='/example1' className={({isActive}) => 
                `${style.navItem} ${isActive ? style.active : ''}`
            }>
                  <SettingsIcon />
            </NavLink>
            <NavLink to='/example2' className={({isActive}) => 
                `${style.navItem} ${isActive ? style.active : ''}`
            }>
                  <LightModeIcon />
            </NavLink>
        </div>
    )
}

对应样式调整

.sidebarContainer{
    background: black;
}
.sidebarContainer a{
    text-decoration: none;
    color: gray;
    width: 100%;
} 
.navItem {
    width: 100%;
    padding: 1rem 0;
    cursor: pointer;
    border-right: 4px solid transparent;
    transition: all 0.3s ease 0s !important;
    list-style: none;
    padding-left: 1.3rem;
    display: flex;
    align-items: center;
}
.navItem:hover, .navItem.active {
    border-right: 4px solid red;
}
.navItem:hover svg, .navItem.active svg {
    color: red;
}
.navItem svg {
    font-size: 1.6rem !important;
    transition: all 0.3s ease 0s !important;
}

内容的提问来源于stack exchange,提问作者s.khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 06:48:00