1

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

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

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

这是这样做的正确方法吗?或者,还有更好的方法?

4

2 回答 2

1

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

于 2021-09-07T23:57:23.867 回答
0

创建一个活动类名

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,或者如果有查询字符串,您还将获得查询字符串。

于 2021-11-14T02:18:21.670 回答