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 類別前加上 !
,讓它們在連結啟用時變得重要。