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

React实现仅为当前选中链接切换active类的方法

解决头部链接单独切换current类的问题

你当前的问题出在只用了一个布尔值isActive控制所有链接的类状态,所以点击任意链接都会让所有链接一起切换current类。要实现仅选中的链接添加类,需要把状态改成记录当前选中的具体链接标识(比如链接的href值)。

修改后的代码实现:

  1. 调整状态定义
// 初始值可以设为默认选中的链接(比如"#home"),或者空字符串表示初始无选中
const [activeLink, setActiveLink] = useState("#home");
  1. 编写设置当前选中链接的函数
const setCurrentLink = (href) => {
  setActiveLink(href);
};
  1. 更新链接的渲染逻辑
    每个链接判断自身的href是否等于activeLink,以此决定是否添加current类,点击时传递自身的href值:
<li>
  <a 
    className={activeLink === "#home" ? "current" : null} 
    href="#home" 
    onClick={() => setCurrentLink("#home")}
  >
    Home
  </a>
</li>
<li>
  <a 
    className={activeLink === "#about" ? "current" : null} 
    href="#about" 
    onClick={() => setCurrentLink("#about")}
  >
    About
  </a>
</li>
<li>
  <a 
    className={activeLink === "#contact" ? "current" : null} 
    href="#contact" 
    onClick={() => setCurrentLink("#contact")}
  >
    Contact
  </a>
</li>

优化方案(减少重复代码)

如果链接数量较多,可以先定义链接数据数组,再用map循环渲染,避免重复写相同的结构:

// 定义链接数据
const links = [
  { href: "#home", text: "Home" },
  { href: "#about", text: "About" },
  { href: "#contact", text: "Contact" }
];

// 渲染链接
{links.map(link => (
  <li key={link.href}>
    <a
      className={activeLink === link.href ? "current" : null}
      href={link.href}
      onClick={() => setCurrentLink(link.href)}
    >
      {link.text}
    </a>
  </li>
))}

这样点击任意链接时,只会更新activeLink为当前链接的href,从而只有该链接会添加current类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:45:32