创建一个活动类名
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,或者如果有查询字符串,您还将获得查询字符串。