[英]Next.js setting current active class with Link and router
I wanted to set an active class to the current page, but I'm missing something.我想为当前页面设置一个活动类,但我遗漏了一些东西。
<Link href={`/projects/${project.id}`}>
<a
className={`${
router.pathname === `/projects/${projects.id}`
? "active"
: ""
}`}
>
{project.title}
</a>
</Link>
Not sure if this is the correct way, because when I console log router.pathname
, I get /projects/[id]
不确定这是否是正确的方法,因为当我控制台日志
router.pathname
,我得到/projects/[id]
Is this the correct way of doing this?这是这样做的正确方法吗? or is there a better way?
或者,还有更好的方法?
You could use router.asPath
in that sense.你可以在这个意义上使用
router.asPath
。
https://nextjs.org/docs/api-reference/next/router#router-object https://nextjs.org/docs/api-reference/next/router#router-object
Just remember that it uses the literal path in the browser, with query strings and anchors.请记住,它使用浏览器中的文字路径,以及查询字符串和锚点。
Create an Active Classname创建活动类名
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>;
}
You can use this reusable component in any part of your project like this:您可以在项目的任何部分使用这个可重用组件,如下所示:
<ActiveLink href={hrefOfPage}>
<a>{project.title}</a>
</ActiveLink>
as href
, you get the current path of page, and it will be exact path.作为
href
,您将获得页面的当前路径,它将是确切路径。 instead of [id]
you will get the real Id, or if there is a query string you will also get the query string.您将获得真实的 Id 而不是
[id]
,或者如果有查询字符串,您也将获得查询字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.