简体   繁体   English

如何获得活动链接以使用 Next.js 中的动态子路径

[英]How to get active link to work with dynamic sub paths in Next.js

I am using next/router to check for the current pathname and then conditionally rendering an active className.我正在使用 next/router 检查当前路径名,然后有条件地呈现一个活动的类名。

Here is what I am doing:这是我正在做的事情:

import { useRouter } from 'next/router';

const router = useRouter();

{
  navigation.map((item) => (
    <Link href={item.href}>
      <a
        key={item.name}
        className={classNames(
          router.pathname === item.href
            ? 'text-purple-700'
            : 'text-gray-500 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white',
          'px-3 py-2 text-base font-medium',
        )}
        aria-current={item.current ? 'page' : undefined}
      >
        {item.name}
      </a>
    </Link>
  ));
}

The issue is I'm also trying to display the active className for dynamic sub routes.问题是我还试图显示动态子路由的活动类名。 For example /item.href/{id}, so it could be /blog/1.例如 /item.href/{id},所以它可能是 /blog/1。

Is it possible to achieve this?有可能实现这一目标吗?

It is possible, you can get the id from router params with有可能,您可以从路由器参数中获取 id

const {id} = router.query

then your matching condition to check the route然后你的匹配条件来检查路线

router.pathname === item.href.replace('[id]', id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 next.js 中跟踪活动链接? - How to track active link in next.js? 如何在 Next.js 上的活动页面上设置链接组件的样式 - How to style Link component when on active page on Next.js 当路由在 Next.js 中处于活动状态时定位活动链接 - Target Active Link when the route is active in Next.js Next.js中如何获取特定的动态DOM元素 - How to get specific dynamic DOM elements in Next.js 来自公共文件夹的 Next.js 图像未在动态路径上加载 - Next.js image from public folder not loading on dynamic Paths 如何在 static S3/CloudFront 网站托管上呈现动态 Next.js 路径? - How to render dynamic Next.js paths on static S3/CloudFront website hosting? 为 Next.js 中的导航链接添加活动 class - Adding active class for nav link in Next.js Next.js 使用链接和路由器设置当前活动类 - Next.js setting current active class with Link and router 即使我在页面上,链接在 next.js 中也无效 - Link not active in next.js even when I am on the page 在 Link 组件中使用“as”道具时,Next.js 具有包罗万象的动态链接(即 [[...slug]])不起作用 - Next.js dynamic link with catch-all (ie. [[...slug]]) does not work when using the "as" prop in Link component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM