您应该在 tailwindCSS 中的 className 上使用
active
变体。
<Link
to="/home"
className="text-gray-300 active:text-blue-500"
>
home
</Link>
您确实需要首先定义如何确定是否添加该类。
在我看来,你想改为循环浏览你的项目:
const isCurrentPage = (href: string) => {
// return true if `href` is the current path, many ways you could do this
}
// loop through your items and conditionally add the class if active...
['/home', '/invoices', '/forms'].map(href => <Link key={href} href={href} className={isCurrentPage(href) ? 'active' : ''} />
您的
isCurrentPage
功能取决于您的应用程序逻辑和设置;你可能可以依靠像window.location.pathname.indexOf(href) === 0
这样的逻辑来开始。
当 NavLink 组件被视为活动时,默认情况下会自动接收“活动”类,从而允许您应用 CSS 来设置样式。 因此,在您的index.css文件中,添加:
@tailwind base;
@tailwind components;
@tailwind utilities;
.active{
/* Add whatever CSS style will make your link look active. The example below (in my case) */
@apply block py-2 pl-3 pr-4 text-white bg-orange-700 rounded md:bg-transparent md:text-orange-700 md:p-0 underline;
}
就是这样。希望这有帮助!