[英]Anchor Tag in Next.js
我正在嘗試在 Next.js 中使用錨標記
當我設置它並單擊鏈接時,我沒有收到任何控制台錯誤,但頁面沒有跳轉到 id 標簽。
github上的這個問題表明人們需要弄清楚很多自定義代碼才能使用錨點。 那不可能是對的。
我有:
const links = [
{ label: 'Solutions', href: '#solutions', id: 'solutions' },
]
<NavLink.Desktop key={index} href={link.href} id={link.id}>
{link.label}
</NavLink.Desktop>
我沒有收到任何錯誤,但頁面沒有跳轉到 ID 為“解決方案”的標簽。
有誰知道如何解決這個問題,或者在哪里可以找到關於如何解決的想法 - 使用錨標記需要復雜的自定義代碼是不可能的?
正如@juliomalves 在評論中所說,您必須在必須導航到的元素中指定id屬性。 不在錨標簽上。
錨點的 id 應該設置在您要鏈接到的元素上,而不是設置在鏈接本身上。
下面的代碼在 Next.js 中對我有用 -
export default function Home() {
return (
<div>
<a href="#secion">Click</a>
<section
style={{ marginTop: "1000px", marginBottom: "1000px" }}
id="secion"
>
<h1>Test</h1>
</section>
</div>
);
}
你的代碼應該是這樣的 -
const links = [{ label: 'Solutions', href: '#solutions', id: 'solutions' }]
<NavLink.Desktop
key={index}
href={link.href}
// id={link.id} - This is wrong, as you're referring to the same element
>
{link.label}
</NavLink.Desktop>
// Rather set the id attribute in a separate div/section element
<div id={link.id}>
<h2>Solutions</h2>
</div>
也許試試
const links = [
{ label: 'Solutions', href: '#solutions', id: 'solutions' },
]
<NavLink.Desktop key={index} href={links[0].href} id={links[0].id}>
{link.label}
</NavLink.Desktop>
因為您在 links 數組中只有 1 個元素,如果您有多個元素,則只需映射到該數組
可以使用 Router.push 以編程方式滾動到錨點:
import { useRouter } from 'next/router'
const Foo = () => {
const { push } = useRouter()
const handleClick = () => {
push("#blah")
}
return (
<div>
<button onClick={handleClick}>Scroll</button>
<div>Foo</div>
<div>Bar</div>
<div id="blah">Blah</div>
</div>
)
}
Next.js 識別出您傳遞的不是指向新頁面的鏈接的內容,並將它(在示例中#blah
)連接到 URL 的末尾。
從 next/link 閱讀有關 Link 的信息,它是一個內置功能。
https://nextjs.org/docs/api-reference/next/link
https://github.com/vercel/next.js/blob/canary/examples/hello-world/pages/index.js#L7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.