如何更改 React-Next.js 中的导航电流?

How can I change navigation current in React-Next.js?

我正在使用此代码进行页眉导航。

const navigation = [
  { name: 'Main', href: '/', current: true },
  { name: 'Test', href: '/test', current: false },
  { name: 'Test 2', href: '#', current: false },
  { name: 'Test 3', href: '#', current: false },
]

在html中:

{navigation.map((item) => (
    <a
        key={item.name}
        href={item.href}
        className={classNames(item.current ? 'bg-gray-900 text-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white', 'px-3 py-2 rounded-md text-sm font-medium')}
        aria-current={item.current ? 'page' : undefined}
    >
        {item.name}
    </a>
))}

如何在路由时将当前部分更改为“真实”?

我认为您不需要为此用例更改数组中某一项的值。

在这种情况下,您可以检查当前路径是什么,您可以在路由器中找到该路径。然后你应该检查当前路径是否与 href 之一匹配。

const NavComponent = () => {
    const router = useRouter();

    return navigation.map((item) => (
        <a
            key={item.name}
            href={item.href}
            className={classNames(
                router.asPath === item.href
                    ? 'bg-gray-900 text-white'
                    : 'text-gray-300 hover:bg-gray-700 hover:text-white',
                'px-3 py-2 rounded-md text-sm font-medium'
            )}
            aria-current={router.asPath === item.href ? 'page' : undefined}
        >
            {item.name}
        </a>
    ));
};