React中组件的滚动滚动位置

问题描述 投票:0回答:1

我有一个带有main且带有overflow: auto标签的组件。根据滚动高度,我需要渲染一个不同的元素。如何在React中获得元素滚动位置?

基本要点是这样:

function App() {
  return (
    <div>
      <main
        style={{
          backgroundColor: "red",
          overflow: "auto",
          height: "500px",
          padding: "5px"
        }}
      >
        Please Track Me!
        <div
          style={{ backgroundColor: "blue", color: "white", height: "5000px" }}
        >
          Inner
        </div>
      </main>
    </div>
  );
}

我需要以某种方式跟踪main(使用overflow: auto)的滚动位置。

reactjs scroll position scrollbar
1个回答
1
投票

您的主要组件必须具有参考。https://reactjs.org/docs/refs-and-the-dom.html另外,您将在组件中使用一个名为onScroll的事件来更新它。检查一下

class ScrollAwareDiv extends React.Component {
  constructor(props) {
    super(props)
    this.myRef = React.createRef()
    this.state = {scrollTop: 0}
  }

  onScroll = () => {
    const scrollY = window.scrollY //Don't get confused by what's scrolling - It's not the window
    const scrollTop = this.myRef.current.scrollTop
    console.log(`onScroll, window.scrollY: ${scrollY} myRef.scrollTop: ${scrollTop}`)
    this.setState({
      scrollTop: scrollTop
    })
  }

  render() {
    const {
      scrollTop
    } = this.state
    return (
      <div
        ref={this.myRef}
        onScroll={this.onScroll}
        style={{
          border: '1px solid black',
          width: '600px',
          height: '100px',
          overflow: 'scroll',
        }} >
        <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
        <p>ScrollTop is {scrollTop}</p>
        <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
        <p>ScrollTop is {scrollTop}</p>
        <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
        <p>ScrollTop is {scrollTop}</p>
        <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
        <p>ScrollTop is {scrollTop}</p>
        <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
        <p>ScrollTop is {scrollTop}</p>
        <p>This demonstrates how to get the scrollTop position within a scrollable react component.</p>
        <p>ScrollTop is {scrollTop}</p>
      </div>
    )
  }
}

ReactDOM.render(
  <ScrollAwareDiv />,
  document.getElementById('root')
);

https://codepen.io/JohnReynolds57/pen/NLNOyO

© www.soinside.com 2019 - 2024. All rights reserved.