[英]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.