NextJs - 滚动到同一页面中的某个部分的链接

Sac*_*tus 32 reactjs next.js

我正在使用 NextJs。我想在我的标题部分创建一个链接。此链接应通过滚动将用户带到同一页面上的 TestimonialsSection。

        <Link href={"#TestimonialsSection"}>
          <a className={styles.Designation}>Mentor</a>
        </Link>
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的代码,但没有成功。但 URL 发生了变化。提前致谢

小智 64

在普通 HTML 中你会做这样的事情

<a href="#first-section">My first section</a>
<a href="#second-section">My second section</a>

<div id="first-section">SECTION 1</div>
<main id="second-section">SECTION 2</main>
Run Code Online (Sandbox Code Playgroud)

在 NextJS 中你会得到类似的东西。您可以使用组件,而不是使用锚标记进行链接Link

<Link href="#first-section">My first section</Link>
<Link href="#second-section">My second section</Link>

<div id="first-section">SECTION 1</div>
<main id="second-section">SECTION 2</main>
Run Code Online (Sandbox Code Playgroud)

这样就可以了。但是,如果您希望起始 URL 为www.my-site.com/#second-section,则需要将 Link 组件的scrollprop 设置为false。前任:

...
<Link href="#second-section" scroll={false}>My second section</Link>
...
Run Code Online (Sandbox Code Playgroud)

确保您的节/div,即目标元素已正确设置ID#属性,并且相应的锚链接具有ID名称#前缀

这是官方 NextJS 文档https://nextjs.org/docs/api-reference/next/link

希望这能解决您的问题。

  • 这个答案对我 nextjs13 不起作用 (6认同)
  • 好的,明白了,现在一切都清楚了。我只是对你回答中的那部分感到困惑,现在一切都好了。谢谢 (2认同)

小智 6

尝试一下这个解决方案,我正在使用 TypeScript,所以这个答案肯定适用于 TypeScript Next.js

export default function Home() {

  // let's make a function that receive the specific element_id as string and scroll into that element_id
  const scrolltoHash = function (element_id: string) {
    const element = document.getElementById(element_id)
    element?.scrollIntoView({ behavior: "smooth", block: "end", inline: "nearest" });
  }


  return (
    <div>

      {/* attach that function with onClick event to an clickable element */}
      <div onClick={() => scrolltoHash('contact')}>
        <span>Click me to Scroll</span>
      </div>

      {/* ...imagine lot of sections/code here */}


      <section id="contact">
        {/* this is the section we want to scroll it could be any element not just limited to section but must have an unique ID. */}
      </section>

      
      
      {/* ...imagine lot of sections/code here */}

    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)