Next.js 14中如何从路由获取当前哈希值?
在Next.js 14.0.3中获取URL哈希值并设置导航激活样式
Next.js的usePathname和useParams不会返回URL中的哈希片段(#开头的部分)——因为哈希属于浏览器端的内容,Next.js路由系统不处理这部分信息。要实现根据哈希值设置导航激活样式,直接用浏览器的window对象操作即可,具体代码如下:
完整导航组件实现
"use client"; import { useEffect, useState } from "react"; function NavBar() { const [activeHash, setActiveHash] = useState<string>(""); useEffect(() => { // 更新当前激活的哈希值 const syncActiveHash = () => { setActiveHash(window.location.hash); }; // 页面加载时初始化 syncActiveHash(); // 监听哈希变化,实时更新状态 window.addEventListener("hashchange", syncActiveHash); // 组件卸载时清理监听 return () => window.removeEventListener("hashchange", syncActiveHash); }, []); // 导航项列表 const navItems = [ { hash: "#home", label: "首页" }, { hash: "#about", label: "关于" }, { hash: "#blog", label: "博客" }, ]; return ( <nav> <ul style={{ listStyle: "none", display: "flex", gap: "1rem" }}> {navItems.map((item) => ( <li key={item.hash}> <a href={item.hash} style={{ textDecoration: activeHash === item.hash ? "underline" : "none", color: activeHash === item.hash ? "#2563eb" : "#333", fontWeight: activeHash === item.hash ? "600" : "normal", }} > {item.label} </a> </li> ))} </ul> </nav> ); } export default NavBar;
核心逻辑说明
- 获取哈希值:
window.location.hash直接返回当前URL的哈希部分,比如http://localhost:3000/#about会返回#about。 - 实时同步哈希变化:通过
hashchange事件监听哈希值的变化,确保用户点击导航项或手动修改URL时,激活状态能实时更新。 - 避免内存泄漏:组件卸载时移除事件监听,这是客户端组件的常规操作。
这样就能精准根据URL哈希值为对应的导航项设置激活样式了。
内容的提问来源于stack exchange,提问作者Ruhul Amin
相关产品推荐
相关产品推荐

