NavLink 组件

如果你想为你的链接添加 `active` 状态,你可以使用此解决方案。NavLink 组件增强了 Qwik 的 `<Link>` 组件,通过添加

  • **活动状态**: 当链接 href 与当前 URL 路径名匹配时,应用一个类。

这允许为导航设置活动状态的样式。

工作原理

在幕后,NavLink 使用 `useLocation` 钩子来获取导航状态。它检查链接 href 是否与当前 URL 路径名匹配以设置 activeClass。这使 NavLink 能够根据导航自动了解活动状态。

import { Slot, component$ } from '@builder.io/qwik';
import { Link, useLocation, type LinkProps } from '@builder.io/qwik-city';
 
type NavLinkProps = LinkProps & { activeClass?: string };
 
export const NavLink = component$(
  ({ activeClass, ...props }: NavLinkProps) => {
    const location = useLocation();
    const toPathname = props.href ?? '';
    const locationPathname = location.url.pathname;
 
    const startSlashPosition =
      toPathname !== '/' && toPathname.startsWith('/')
        ? toPathname.length - 1
        : toPathname.length;
    const endSlashPosition =
      toPathname !== '/' && toPathname.endsWith('/')
        ? toPathname.length - 1
        : toPathname.length;
    const isActive =
      locationPathname === toPathname ||
      (locationPathname.endsWith(toPathname) &&
        (locationPathname.charAt(endSlashPosition) === '/' ||
          locationPathname.charAt(startSlashPosition) === '/'));
 
    return (
      <Link
        {...props}
        class={`${props.class || ''} ${isActive ? activeClass : ''}`}
        
      >
        <Slot />
      </Link>
    );
  }
);

用法

你可以使用 NavLink,并添加 `activeClass` 属性

import { component$ } from '@builder.io/qwik';
import { NavLink } from '..';
 
export default component$(() => {
  return (
    <>
      Links
      <div>
        <NavLink href="/docs" activeClass="text-green-600">
          /docs
        </NavLink>
      </div>
      <div>
        <NavLink
          href="/demo/cookbook/nav-link/example/"
          activeClass="text-green-600"
        >
          /demo/cookbook/nav-link/example/
        </NavLink>
      </div>
    </>
  );
});

Tailwind

如果你使用的是 Tailwind CSS,请确保编辑你的 tailwind 配置文件,并将 `important=true` 添加到你的导出中,然后在使用 `activeClass="!text-green-600"` 的 CSS 类之前添加 `!`,以使它们在链接处于活动状态时具有重要性。

贡献者

感谢所有帮助改进这份文档的贡献者!

  • Adbib