maj*_*jid 12 javascript reactjs next.js
如何定位 Next.js 中的活动链接 (next 13)
const Sidebar = () => {
const link = [
{
label: ' Home',
path: '/',
},
{
label: ' About',
path: '/about',
}
]
return (
<div>
{sidebarLink.map((link, index) =>
<Link
key={link.index}
href={link.path}>
</Link>
)}
</div>
)
}
export default Sidebar
Run Code Online (Sandbox Code Playgroud)
我尝试了一切都无济于事
不太理想,但这就是我正在做的事情。
"use client"; // if you are planing to use it in the component which is not marker with use client directive this is a must
import Link, { LinkProps } from "next/link";
import { usePathname } from "next/navigation"; // usePathname is a hook now imported from navigation
const ActiveLink = ({
children,
...rest
}: { children: React.ReactNode } & LinkProps) => {
const { href } = rest;
const pathName = usePathname();
const isActive = pathName === href;
return (
// you get a global isActive class name, it is better than
// nothing, but it means you do not have scoping ability in
// certain cases
<Link {...rest} className={isActive ? "active" : ""}>
{children}
</Link>
);
};
export default ActiveLink;
Run Code Online (Sandbox Code Playgroud)
我熟悉的最佳解决方案是使用 Next.js 中的“布局段”。
\n需要注意的是,它还可以与 i18n 路由 \xe2\x80\x93 无缝协作,例如:/en/about/ 等。
\n我强烈建议您尝试一下:)
\n\'use client\'\n\nimport { items } from \'@/utils/nav\'\n/* example\nexport const items = [\n {\n id: 1,\n title: \'Home\',\n href: \'/\',\n activeSegment: null,\n },\n {\n id: 2,\n title: \'About\',\n href: \'/about\',\n activeSegment: \'about\',\n },\n ...\n ]\n*/\n\nimport Link from \'next/link\'\nimport { useSelectedLayoutSegment } from \'next/navigation\'\n\n...\n\n// Inside you client component\nconst activeSegment = useSelectedLayoutSegment()\n\n....\n\n<nav>\n {items.map((item) => (\n <Link\n key={item.id}\n href={item.href}\n className={activeSegment === item.activeSegment ? \'text-primary font-semibold\' : \'text-muted-foreground\'}\n >\n {item.title}\n </Link>\n ))}\n</nav>\n\n...\nRun Code Online (Sandbox Code Playgroud)\n\n