Scroll to element in React

时间:2016-05-11 13:43:31

标签: javascript html reactjs

I have a ref on all the large section headers on a page. The page is very long and renders well passed 100vh. The section that is scrollable is a fairly nested div, also with a ref. Given the refs of the section headers, and the ref of the inner container (can't use window.scrollTo etc.) how can would I build a "on click, go to section".

<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)

I have been unable to find a consistent way to do this using scrollTop and getBoundingClientRects().top on the section refs.

1 个答案:

答案 0 :(得分:1)

我认为您可以使用旧方法从链接导航到某个部分 e.g。

这是我要导航的部分

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

并在我提供的锚链接

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