Next.js:实现多根布局后更改活动链接颜色的问题

7lrncoxx  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(84)

我目前正在使用Next.js开发一个应用程序,并使用官方Next.js文档中的多根布局(https://nextjs.org/docs/app/building-your-application/routing/route-groups#creating-multiple-root-layouts)。因为我需要为每条路线单独设置样式。
然而,在实现多个根布局后,我遇到了一个问题,活动链接的颜色没有按预期变化,即使它在变化前工作得很好。
抱歉,因为我是初学者,关于next.js最新版本的信息不多
下面是我处理活动链接颜色的相关代码:

import { useState } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";

const Sidebar = () => {
    const [isMobileMenuVisible, setIsMobileMenuVisible] = useState(false);
    const pathname = usePathname();

    const isActive = (href) => {
        if (pathname.startsWith(href)) {
            return "text-[#909090]";
        }
        return "";
    };

    const toggleMobileMenu = () => {
        setIsMobileMenuVisible(!isMobileMenuVisible);
    };

    return (
         DACHI-GIORGI GARUCHAVA
         {/* Mobile dropdown menu */}
         <button
            className="text-[#484848] no-underline cursor-pointer font-MPlus1 leading-6 font-thin tracking-wider mb-2"
            onClick={toggleMobileMenu}
            Menu
            {isMobileMenuVisible && (
                The Witness
               {/* Add other links here */}
            )}
           {/* Desktop link list */}
           Invasive Modification
           {/* Add other links here */}
       );
};

export default Sidebar;

字符串

isActive函数检查
路径名来确定链接是否处于活动状态,并相应地应用特定的文本颜色。在我开始使用多个根布局之前,这种逻辑工作得很好,我需要单独设置路由的样式。
任何帮助将不胜感激

njthzxwz

njthzxwz1#

所以我运行了你在codesandbox中分享的GitHub repo,看起来这个问题与root布局无关。您的isActive方法按预期工作,并且它还将text-[#909090]类名添加到标记中。
这里的主要问题是,您使用@apply指令创建了一个名为project_link的自定义类,并且您在该类中指定的颜色实际上覆盖了通过text-[#909090]添加的颜色,以下是标记的屏幕截图以供参考:


的数据
因此,解决这个问题的最好方法是不使用您在project_link中添加的类抽象,而是直接内联应用类,并根据链接是否活动来有条件地应用颜色,因为创建这样的抽象会破坏使用顺风的目的。他们甚至在他们的文档中有一节说明为什么你应该避免像这样过早的类抽象。
如果你想避免重复,最好为这些链接创建一个单独的组件,并使用它,这会使isActive作为一个prop从父组件传递过来。在该组件中,您可以像这样应用类:

...
  className={`no-underline cursor-pointer font-MPlus1 leading-6 font-thin tracking-wider ${isActive ? 'text-[#909090]' : 'text-[#484848]'}`}
  ...

字符串

相关问题