我正在开发一个 Next.js 项目,我正在尝试使用 URL 哈希导航到页面上具有
id='section'
的特定部分。
当我单击带有
href='#section'
的链接时,它会正确滚动到所需的部分。
但是,当我手动将 URL 中的哈希更改为“www.example.com#section”时,它不会导航到该部分。
有没有办法在不使用 useRouter() 的情况下修复它?
编辑:
我注意到有时有效,有时无效。
例如,当我从页面“www.example.com”开始然后添加“#section”时,它确实滚动到相应的部分。
但是当我直接输入“www.example.com#section”时却没有。
这种行为有解释吗?
我正在使用 Next
14.2.15
,也遇到了这个问题。我无法在我的应用程序或配置中检测到任何会更改访问时处理 URL 中哈希值的默认值的内容。
我最终检查了客户端组件的哈希值并将其推送到 Next 的路由器上:
'use client'
// first client component to be rendered in app
import { useRouter } from 'next/navigation'
import { PropsWithChildren, useEffect } from 'react'
export default function ClientWrapper({ children }: PropsWithChildren) {
const router = useRouter()
useEffect(() => {
if (window.location.hash) {
const id = window.location.hash
const element = document.getElementById(id.substring(1))
if (element) {
router.push(id)
}
}
}, [])
return <>{children}</>
}