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

如何使用React Router DOM和SCSS设置激活态NavLink样式?

问题

基于React+TypeScript开发项目,采用SCSS编写样式,尝试为react-router-dom中的NavLink元素设置激活态样式却未生效。项目无相关报错,已排除依赖干扰,且通过开发者工具可见激活类已显示在元素上,但样式仍不生效。相关代码如下:

菜单组件(JSX)

const Menu: FC<MenuProps> = () => {
  return(
  <div className={styles.Menu}>
    <NavLink to="/profile" >
      <div className={styles.navItem}>
        <FaHouseUser />
        <p>Profile</p>
      </div>
    </NavLink>
    <hr />
    
    <NavLink to="/favorites" >
      <div className={styles.navItem}>
        <FaRegHeart />
        <p>Favorites</p>
      </div>
    </NavLink>
    <hr />

    <NavLink to="/explore" >
      <div className={styles.navItem}>
        <FaSearch />
        <p>Explore</p>
      </div>
    </NavLink>
    <hr />

    <NavLink to="/home" >
      <div className={styles.navItem}>
        <FaHome />
        <p>Home</p>
      </div>
    </NavLink>
  </div>
  )
}

SCSS样式

& > a {
  width: 25%;
  height: 100%;

  & > .navItem {
    @extend %flexCol;
    align-items: center;
    justify-content: center;
    gap: 0.25em;

    & > svg {
      color: rgba($colorPrimary, 0.75);
      font-size: 1.5em;
    }

    & > p {
      color: rgba($colorPrimary, 1);
      font-size: 0.75em;
    }
  }
}
解决方案

1. 利用全局激活类结合SCSS设置样式

NavLink默认会给激活元素添加active全局类,由于你使用了CSS Modules,需要用:global()包裹该类选择器才能正确命中:

& > a {
  width: 25%;
  height: 100%;

  & > .navItem {
    @extend %flexCol;
    align-items: center;
    justify-content: center;
    gap: 0.25em;

    & > svg {
      color: rgba($colorPrimary, 0.75);
      font-size: 1.5em;
    }

    & > p {
      color: rgba($colorPrimary, 1);
      font-size: 0.75em;
    }
  }

  // 激活态样式
  &:global(.active) > .navItem {
    & > svg {
      color: rgba($colorPrimary, 1);
      font-size: 1.8em;
    }
    & > p {
      color: rgba($colorPrimary, 1);
      font-weight: bold;
    }
  }
}

2. 通过NavLink的className回调自定义激活类

在JSX中给NavLink传入回调函数,根据isActive状态返回对应类名:

<NavLink 
  to="/profile" 
  className={({ isActive }) => `${styles.navLink} ${isActive ? styles.active : ''}`}
>
  <div className={styles.navItem}>
    <FaHouseUser />
    <p>Profile</p>
  </div>
</NavLink>

然后在SCSS中直接定义激活类样式:

& > a {
  width: 25%;
  height: 100%;

  // 激活态样式
  &.active > .navItem {
    & > svg {
      color: rgba($colorPrimary, 1);
      font-size: 1.8em;
    }
    & > p {
      color: rgba($colorPrimary, 1);
      font-weight: bold;
    }
  }

  & > .navItem {
    // 原有样式...
  }
}

3. 额外注意点

  • 路由匹配问题:如果需要精确匹配(避免子路由激活父导航),给NavLink添加end属性,比如<NavLink to="/home" end>。
  • 样式优先级:确保激活态选择器权重不低于原有样式,避免被覆盖。

内容的提问来源于stack exchange,提问作者viko randazo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:07:01