NextJS React Tailwind CSS 导航栏主动样式

NextJS React Tailwind CSS Navbar Active Styling

好久没玩过React,刚开始学习Next.Js。我很好奇如何根据当前布尔值“current”true/false 在 Tailwind CSS 中更改 Navbar 的背景 true/false 用户使用 Next Router 在哪个页面上。

看起来很简单,但对我来说理解起来有点复杂。该代码最初来自 Tailwind CSS 示例之一,并且有一个带有 href 的 links 数组和带有 true/false 的当前值,当设置为 true 时填充背景。当您更改任何“true”时,我想要的背景渐变就会出现,但我一直试图让它在访问的相应页面上更新 link。

如果有人能指导我正确的方向,我将不胜感激。

这是我的 header 代码:

/components/header.js

我还制作了一个layout component组件并把它包裹在我的_app.js.

这是其他组件的其余代码:

_app.js

/components/layout/main.js

我的导航栏目前看起来像这样: Navbar Image

如果您需要我的其他代码,我很乐意提供。

而不是将 current 存储在 navigation 数组中,您可以根据当前 url 使用 router.asPath(参见文档 here)。

const isActive = router.asPath === item.href;

--

{
  navigation.map((item) => {
    const isActive = router.asPath === item.href;
    return (
      <NextLink key={item.name} href={item.href} passHref>
        <a
          className={classNames(
            isActive
              ? "text-black font-bold bg-gradient-to-r from-pink-300 via-purple-300 to-indigo-400"
              : "text-gray-700 hover:bg-gray-200 hover:text-gray-500 hover:underline hover:underline-offset-2",
            "px-3 py-2 rounded-md text-sm font-medium font-mono"
          )}
        >
          {item.name}
        </a>
      </NextLink>
    );
  });
}