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

React Router 6.8中如何基于NavLink激活状态动态修改to属性?

React Router 6.8 实现NavLink动态切换跳转路径

问题分析

你想让NavLink像动态设置className那样,基于激活状态(isActive)动态修改to属性,实现点击导航项切换显示/隐藏<Artist />组件,但NavLink的to属性并不支持直接接收带isActive的回调函数(这和className的回调逻辑不同),所以需要换一种方式实现。

实现方案

通过组件内部维护状态来跟踪激活状态,结合useLocation初始化状态,点击时翻转状态并动态设置to和className:

  1. 导入所需的React和React Router Hooks:
import { useState, useEffect } from 'react';
import { NavLink, useLocation } from 'react-router-dom';
  1. 在组件内部定义状态和路径判断逻辑:
const location = useLocation();
const [isArtistActive, setIsArtistActive] = useState(false);

// 初始化时根据当前路径设置激活状态
useEffect(() => {
  const artistPath = `/artist/${currentMotive.artist.slug.current}`;
  setIsArtistActive(location.pathname === artistPath);
}, [location.pathname, currentMotive.artist.slug.current]);
  1. 修改NavLink组件代码:
<NavLink
  className={isArtistActive ? "isActive" : "isNotActive"}
  to={isArtistActive ? `/motive/${currentMotive.slug.current}` : `/artist/${currentMotive.artist.slug.current}`}
  key={currentMotive.artist.slug.current}
  onClick={() => setIsArtistActive(prev => !prev)}
>
  {currentMotive.artist.name}
</NavLink>

原理说明

  • 用useState维护isArtistActive状态,直接控制导航项的激活样式和跳转目标。
  • useEffect监听路由变化,初始化时判断当前路径是否为艺术家页面,确保刷新页面时状态与路由匹配。
  • 点击NavLink时翻转isArtistActive状态,同步切换跳转路径,实现“开关”式的组件显示/隐藏效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 10:52:12