簡體   English   中英

在 React 中滾動到元素

[英]Scroll to element in React

我在頁面上的所有大節標題上都有一個參考。 該頁面很長,並且通過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找到一致的方法來做到這一點。

我認為您可以使用舊方法從鏈接導航到某個部分,例如

這是我要導航的部分

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

並在錨鏈接上我提供

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM