在 next.js 应用程序路由器中,如何检查指向页面各部分的活动链接

问题描述 投票:0回答:1

我有一个导航栏,其中一些

Link
指向其他页面,以及 其他链接指向页面的各个部分

我想知道哪个部分当前处于活动状态。我按照文档中的建议尝试了

usePathname
,但这仅显示了激活页面,而不是页面部分:

import { usePathname} from 'next/navigation';

const NavBar = () => {
  const pathname = usePathname();  

  const isActive = (href) => {
    console.log(pathname)
    console.log(href)
    if (pathname.startsWith(href)) {
        return " text-orange-500 animation-active ";
    }
    return " text-black-500 hover:text-orange-500 ";
};

上面的日志总是显示:

/
/#about
/
/#contact

所以

pathname
始终是全局页面。在本例中是主页
/
。但即使当我单击这些部分时,尽管 url 本身发生了变化,但
pathname
也不会更改事件。

如何获取页面内的活动部分?

reactjs path navbar next.js13
1个回答
0
投票

使用 Next.js 中 next/router 中的 useRouter 进行带有哈希片段的内部链接,以访问完整路径(包括哈希),因为 next/navigation 中的 usePathname 仅提供当前路径名而不提供哈希。

import { useRouter } from 'next/router';

const NavBar = () => {
  const { asPath } = useRouter();

  const isActive = (href) => {
    if (asPath.startsWith(href)) {
      return "text-orange-500 animation-active";
    }
    return "text-black-500 hover:text-orange-500";
  };
}

https://github.com/vercel/next.js/discussions/49465

另请检查上面的链接。

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.