如何使用当前页面和语言环境将活动 class 添加到 link?

How to add active class to link with current page and locale?

我有一个副标题菜单,我想在其中添加一个活动 class 到活动页面。问题是当我更改语言环境时。 如果我的 link 看起来像:my-site/my-page - 它有效 但是如果我的 link: my-site/fr/my-page - 不起作用。 另外,使用 Storyblok 无头 CMS。

import { Box, HStack, Link, LinkProps, List, ListItem } from "@chakra-ui/react";
import NextLink from "next/link";
import React from "react";


type SubHeaderLinkProps = {
  name: string;
  href: string;
  isActive: boolean;
};
const activeLinkStyles: LinkProps = {
  color: "orange.400",
  borderBottom: "1px solid",
  borderColor: "orange.400",
};

const inActiveLinkStyles: LinkProps = { color: "white" };
const SubHeaderLink: React.VFC<SubHeaderLinkProps> = ({
  name,
  href,
  isActive,
}) => (
  
  <ListItem _last={{ base: { pr: 8 }, lg: { pr: 0 } }}>
    <NextLink href={href} passHref>
      <Link
        sx={isActive ? activeLinkStyles : inActiveLinkStyles}
        py={5}
        w="min-content"
        d="block"
        whiteSpace="nowrap"
     >
        {href}
      </Link>
    </NextLink>
  </ListItem>
);

此外,在我使用 SubHeaderLink 组件的地方添加了另一个代码文件。

import {
  SubHeaderLink,
  SubHeaderLinks,
} from "@/components/layout/subHeader/SubHeader";
import { ReactStoryblokComponent, StoryblokLink } from "@/types/storyblok";
import { useRouter } from "next/router";
import { useStoryblokLinkParser } from "storyblok/useStoryblokLinkParser";

type Blok = {
  subHeaderLinks: { _uid: string; linkName: string; href: StoryblokLink }[];
};

const StoryblokSubHeader: ReactStoryblokComponent<Blok> = ({
  blok: { subHeaderLinks },
}) => {
  const { asPath } = useRouter();
  const { getHref } = useStoryblokLinkParser();

  return (
    <SubHeaderLinks>
      {subHeaderLinks.map(({ _uid, href, linkName }) => (
        <SubHeaderLink
          key={_uid}
          href={getHref(href)}
          name={linkName}
          isActive={asPath === getHref(href)}
        />
      ))}
    </SubHeaderLinks>
  );
};

export default StoryblokSubHeader;

asPath 属性 包含当前路径 而没有 locale 值。来自 router object 文档:

asPath: String - The path (including the query) shown in the browser without the configured basePath or locale.

假设 getHref(href) returns 路径中包含语言环境,您需要将其与 asPath 以及语言环境进行比较。

const StoryblokSubHeader: ReactStoryblokComponent<Blok> = ({ blok: { subHeaderLinks } }) => {
    const { asPath, locale, defaultLocale } = useRouter(); // Get the current locale
    const { getHref } = useStoryblokLinkParser();

    const getCurrentPath = () => {
        if (locale === defaultLocale) return asPath

        return `/${locale}${asPath}`
    }

    return (
        <SubHeaderLinks>
            {subHeaderLinks.map(({ _uid, href, linkName }) => (
                <SubHeaderLink
                    key={_uid}
                    href={getHref(href)}
                    name={linkName}
                    isActive={getCurrentPath() === getHref(href)}
                />
            ))}
        </SubHeaderLinks>
    );
};