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

NextJS中ActiveLink组件的使用示例及相关资源咨询

基于官方文档中 useRouter 实现的 ActiveLink 组件,以下是几种常见的使用场景:

1. 基础导航栏使用

假设你已经完成了官方版 ActiveLink 组件的封装,直接在导航栏中引入使用即可:

import ActiveLink from './ActiveLink';

export default function Navbar() {
  return (
    <nav className="nav-container">
      <ActiveLink href="/">
        <a className="nav-item">首页</a>
      </ActiveLink>
      <ActiveLink href="/about">
        <a className="nav-item">关于我们</a>
      </ActiveLink>
      <ActiveLink href="/blog">
        <a className="nav-item">博客</a>
      </ActiveLink>
    </nav>
  );
}

2. 自定义激活样式

如果需要给激活状态的链接添加专属样式,可以在组件封装时支持传入自定义激活类名:

// 支持自定义激活类的 ActiveLink 组件
import { useRouter } from 'next/router';
import Link from 'next/link';
import React from 'react';

export default function ActiveLink({ 
  children, 
  href, 
  activeClassName = 'active-nav-item' 
}) {
  const router = useRouter();
  const isActive = router.asPath === href;

  const childElement = React.Children.only(children);
  const combinedClassName = isActive 
    ? `${childElement.props.className} ${activeClassName}` 
    : childElement.props.className;

  return (
    <Link href={href}>
      {React.cloneElement(childElement, { className: combinedClassName })}
    </Link>
  );
}

// 使用示例
<ActiveLink href="/dashboard" activeClassName="text-primary font-bold">
  <a className="nav-item">控制台</a>
</ActiveLink>

3. 适配动态路由

针对 /posts/[id] 这类动态路由场景,可以通过判断路由路径前缀来匹配激活状态:

// 适配动态路由的 ActiveLink 组件
import { useRouter } from 'next/router';
import Link from 'next/link';
import React from 'react';

export default function ActiveLink({ children, href }) {
  const router = useRouter();
  // 匹配以目标路径开头的路由
  const isActive = router.asPath.startsWith(href);

  const childElement = React.Children.only(children);
  const className = isActive 
    ? `${childElement.props.className} active` 
    : childElement.props.className;

  return (
    <Link href={href}>
      {React.cloneElement(childElement, { className })}
    </Link>
  );
}

// 使用动态路由链接
<ActiveLink href="/posts">
  <a className="nav-item">文章列表</a>
</ActiveLink>
<ActiveLink href="/posts/1">
  <a className="nav-item">第一篇文章</a>
</ActiveLink>

二、获取Next.js相关内容的渠道

  • Next.js官方文档:最权威的资料来源,涵盖API细节、教程和最佳实践
  • 技术问答社区:可以搜索相关问题,获取开发者实际遇到的问题解决方案和经验总结
  • 前端技术博客:不少开发者会分享Next.js的使用技巧、组件封装思路和实战项目案例
  • 开源代码平台:查看优秀的Next.js项目源码,学习ActiveLink等组件的实际应用方式
  • 前端教程网站:有系统的Next.js课程,覆盖路由、组件封装等核心知识点

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 23:59:59