Sak*_*ngh 3 html javascript css next.js tailwind-css
我正在使用 NextJS 和 Tailwind css 来设计顶部导航栏。我希望更改活动链接的文本颜色。下面是我的代码:
const Header = () => {
return(
<header>
<nav className="sd:max-w-6xl mx-auto">
<ul className="flex py-2">
<li className="mr-auto ml-4">
<Link href="/"><a><Image width={80} height={80} src="/images/brand-logo.png" alt="ECT Logo"/></a></Link>
</li>
<li className="mr-4 my-auto hover:text-indigo-600 font-normal font-serif text-brand-darkblue text-xl active:text-indigo-600">
<Link href="/"><a>Home</a></Link>
</li>
<li className="mr-4 my-auto hover:text-indigo-600 font-normal font-serif text-brand-darkblue text-xl active:text-indigo-600">
<Link href="/user/signup"><a>Join</a></Link>
</li>
<li className="mr-4 my-auto hover:text-indigo-600 font-normal font-serif text-brand-darkblue text-xl active:text-indigo-600">
<Link href="/user/login"><a>Login</a></Link>
</li>
</ul>
</nav>
</header>
)
}Run Code Online (Sandbox Code Playgroud)
我还在 tailwind.config.css 中添加了以下内容:
module.exports = {
#
variants: {
extend: {
textColor: ['active'],
},
}Run Code Online (Sandbox Code Playgroud)
尽管如此,活动链接的文本颜色不会改变。
你能指导一下我做错了什么吗?
ptt*_*tts 11
您可能会混淆两件事:
active每当当前按下某个元素时,都会应用 Tailwind CSS 中的前缀。(例如,当您按下链接或按钮时)(https://tailwindcss.com/docs/hover-focus-and-other-states#active)nav项目的 href匹配你不可能用 1 来实现 2,它们是不同的东西。
要在 next.js 中实现 2,您需要获取当前路径,将其与<Link>元素的路径进行比较,如果它们相等,则添加条件 tailwind 类以显示您当前位于相应的页面上。
以下是如何实现 2 的代码示例:
import Link from 'next/link';
import { useRouter } from 'next/router';
export const Header = () => {
const router = useRouter();
return (
<header>
<Link href="/">
<a className={router.pathname == "/" ? "active" : ""}>
Home
</a>
</Link>
</header>
)
}
Run Code Online (Sandbox Code Playgroud)
来源:https ://dev.to/yuridevat/how-to-add-styling-to-an-active-link-in-nextjs-593e
对于你的情况,你可以这样做:
<Link href="/user/signup">
<a className={`mr-4 my-auto hover:text-indigo-600 font-normal font-serif text-xl ${router.pathname == "/user/signup" ? "text-indigo-600" : "text-brand-darkblue"}`}>
Home
</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
小智 7
使用 NavLink 时,它会在链接中添加活动类,但在 tailwindcss 中添加活动状态
最简单的方法是使用像这样的自定义变体
<NavLink to={``} className={'[&.active]:text-indigo-500}>
</NavLink>
Run Code Online (Sandbox Code Playgroud)
这种方式既是纯css,又利用了tailwindcss的强大功能。此外,在没有必要时避免使用状态以避免渲染问题
| 归档时间: |
|
| 查看次数: |
28077 次 |
| 最近记录: |