【问题标题】:Next.js: Link to element in a component on the same pageNext.js:链接到同一页面上组件中的元素
【发布时间】:2022-01-08 10:14:07
【问题描述】:

我正在开发我的第一个 Next.js 项目,并且我有一个单页网站。我已经完成了导航组件,但现在我需要管理链接。

如何添加 <Link /> 组件,它将引用其他组件中的元素(在我的情况下为 <section>)(我的意思是像在纯 HTML 中带有元素 id 的东西:

<a href="#about">About us</a>)?

当滚动位置在特定元素上时是否可以更改 URL slug(例如,当用户滚动到关于我们部分时,slug 将是 domain.com/about 当用户在同一页面上向下滚动到联系人部分时,URL slug 将是 domain.com/contact)?

【问题讨论】:

    标签: reactjs next.js jsx


    【解决方案1】:

    您可以使用上面所说的实现该行为,它会起作用。

    类似这样的代码框:https://codesandbox.io/s/jolly-babycat-4zoqv?file=/pages/index.js

     <div>
          These are the links
          <Link href="#about">
            <a>About</a>
          </Link>
          <Link href="#contact">
            <a>contact</a>
          </Link>
          <div
            style={{
              width: "100%",
              height: "2000px",
              marginTop: 800,
              background: "#ff0"
            }}
          >
            <section ref={aboutRef} id="about" style={{ ...sectionStyle }}>
              About
            </section>
            <section
              ref={contactRef}
              style={{ ...sectionStyle, background: "red" }}
              id="contact"
            >
              Contact
            </section>
          </div>
        </div>
    

    【讨论】:

    • 非常感谢!还有一个问题,是否可以从 slug 中删除 # (将 domain.com/#about 更改为 domain.com/about)?
    猜你喜欢
    • 2020-01-09
    • 2014-04-20
    • 2020-08-31
    • 2016-10-26
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 2021-05-09
    相关资源
    最近更新 更多