【问题标题】:Next.js setting current active class with Link and routerNext.js 使用 Link 和路由器设置当前活动类
【发布时间】:2021-11-04 18:49:19
【问题描述】:

我想为当前页面设置一个活动类,但我遗漏了一些东西。

<Link href={`/projects/${project.id}`}>
  <a
    className={`${
      router.pathname === `/projects/${projects.id}`
        ? "active"
        : ""
    }`}
  >
    {project.title}
  </a>
</Link>

不确定这是否正确,因为当我控制台日志router.pathname 时,我得到/projects/[id]

这是正确的做法吗?还是有更好的方法?

【问题讨论】:

    标签: reactjs react-router next.js nextjs-dynamic-routing


    【解决方案1】:

    你可以在这个意义上使用router.asPath
    https://nextjs.org/docs/api-reference/next/router#router-object
    请记住,它在浏览器中使用文字路径,带有查询字符串和锚点。

    【讨论】:

    • 如果页面上有查询字符串和锚点,有没有更好的方法?
    • 我能想到一些方法。您可以: - 使用 .split('#').split('?') 手动剥离 asPath - 将 activeId 从服务器端一直传递到您的组件 - 使用 router.pathname[id] 替换为 router.query.id
    • 如果有像/projects/${projects.id}/something-else-beyond 这样的网址,但它至少能捕获/projects/${projects.id}/ 怎么办?
    • 如果您的链接即使在嵌套页面中也将保持活动状态,那么我建议使用 activeId 道具想法或简单地比较 router.query.id 属性。
    【解决方案2】:

    创建一个活动类名

    import Link from "next/link";
    import React from "react";
    import { useRouter } from "next/router";
    
    // we are providing here "href" as prop, children is <a/>
    // activeLinkClass incase you want to provide different class in different pages. If you don't, default className "active"
    export default function ActiveLink({ children, activeLinkClass, ...props }) {
      const { pathname } = useRouter();
      let className = children.props.className || "";
      // pathname=/marketplace
      if (pathname === props.href) {
        className = `${className} ${
          activeLinkClass ? activeLinkClass : "active"
        }`;
      }
      // we could write "children" but we would not be able to provide addional props
      //   this is wrapping <a>
      return <Link {...props}>{React.cloneElement(children, { className })}</Link>;
    }
    

    您可以在项目的任何部分中使用此可重用组件,如下所示:

          <ActiveLink href={hrefOfPage}>
              <a>{project.title}</a>
            </ActiveLink>
    

    作为href,你得到了页面的当前路径,它将是确切的路径。而不是[id],你会得到真实的Id,或者如果有查询字符串,你也会得到查询字符串。

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 2021-11-04
      • 1970-01-01
      • 2020-05-14
      • 2021-06-21
      • 2021-03-30
      • 1970-01-01
      • 2021-07-20
      • 2022-01-10
      相关资源
      最近更新 更多