当我学习用于条件 CSS 类组合的 clsx 库时,我尝试通过在导航栏上实现活动链接来尝试它。我创建了这个粗略的导航链接组件。该代码与
pathname === link.href
配合使用效果良好。当我将 link.href
更改为 '/dashboard'
或 '/dashboard/invoice'
时,所有链接都会突出显示,包括给定的链接
初始代码:
'use client';
import clsx from 'clsx';
import Link from 'next/link';
import {usePathname} from 'next/navigation'
const links = [
{ name: 'Home',
href: '/dashboard',
icon: HomeIcon },
{
name: 'Invoices',
href: '/dashboard/invoices',
icon: DocumentDuplicateIcon,
},
{ name: 'Customers',
href: '/dashboard/customers',
icon: UserGroupIcon },
];
export default function NavLinks() {
const pathname = usePathname()
return (
<>
{links.map((link) => {
const LinkIcon = link.icon;
console.log(link.href);
return (
<Link
key={link.name}
href={link.href}
className={clsx('flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3',
{'bg-red-200 text-red-600': pathname === link.href}
)}
>
<LinkIcon className="w-6" />
<p className="hidden md:block">{link.name}</p>
</Link>
);
})}
</>
);
}
最终代码:
'use client';
import clsx from 'clsx';
import Link from 'next/link';
import {usePathname} from 'next/navigation'
const links = [
{ name: 'Home',
href: '/dashboard',
icon: HomeIcon },
{
name: 'Invoices',
href: '/dashboard/invoices',
icon: DocumentDuplicateIcon,
},
{ name: 'Customers',
href: '/dashboard/customers',
icon: UserGroupIcon },
];
export default function NavLinks() {
const pathname = usePathname()
return (
<>
{links.map((link) => {
const LinkIcon = link.icon;
return (
<Link
key={link.name}
href={link.href}
className={clsx('flex h-[48px] grow items-center justify-center gap-2 rounded-md bg-gray-50 p-3 text-sm font-medium hover:bg-sky-100 hover:text-blue-600 md:flex-none md:justify-start md:p-2 md:px-3',
{'bg-red-200 text-red-600': pathname === '/dashboard'}
)}
>
<LinkIcon className="w-6" />
<p className="hidden md:block">{link.name}</p>
</Link>
);
})}
</>
);
}
我碰巧遇到了你的问题。我知道这个问题很久以前就被问过,但无论如何我都会尽力回答。
将
pathname === link.href
更改为 pathname === '/dashboard'
,我能够重新创建所有 <Link>
组件都突出显示的“问题”。我也有一分钟的困惑。我之所以引用“问题”这个词,是因为它实际上并不是一个错误,而只是欺骗了你和我的逻辑混乱。
您使用条件
<Link>
将 pathname === '/dashboard'
组件设置为突出显示。当您导航到 <Link>
时,该条件对于所有 '/dashboard'
组件均成立,这就是它们全部突出显示的原因。