【问题标题】:Scroll to element in React滚动到 React 中的元素
【发布时间】:2020-02-19 16:14:52
【问题描述】:

我在页面上的所有大节标题上都有一个参考。该页面很长,并且很好地通过了100vh。可滚动的部分是一个相当嵌套的 div,也带有一个 ref。鉴于节标题的引用和内部容器的引用(不能使用window.scrollTo 等),我如何构建“点击后转到部分”。

<div>
  <div>
    <button onClick={ // navigate to section }>Navigate</button>
  </div>
  <div>
    <div ref="inner_content">
      <h2 ref="section1">Section 1</h2>
      <h2 ref="section2">Section 2</h2>
      <h2 ref="section3">Section 3</h2>
    </div>
  </div>
</div>

// on navigate, I've tried things like this which have made the page scroll, but I can't understand which scroll/height properties I would need to access to pinpoint where the view should scroll too
this.refs.inner_content.scrollTop(this.refs.section1.getBoundingClientRect().top)

我一直无法找到一致的方法来使用参考部分上的scrollTopgetBoundingClientRects().top

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    我认为您可以使用旧方法从链接导航到某个部分 例如

    这是我要导航的部分

    <div id="section1">
     This is section 1
    </div>
    

    在我提供的锚链接上

     <a href="#section1">Section 1</a>
    

    【讨论】:

    • 这会污染 URL。因此,当这样做时,“#section”被添加到 URL 中,然后如果我刷新页面,它无法加载(因为它是无效路径)
    猜你喜欢
    • 2019-10-18
    • 1970-01-01
    • 2019-12-31
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2013-05-08
    相关资源
    最近更新 更多