简体   繁体   English

使用React JS检测固定高度div的滚动结束

[英]Detecting the end of scroll for a fixed height div using React JS

HTML: HTML:

 <div  className={classes.StoryContentSection}>
          Content...
</div>

CSS: CSS:

.StoryContentSection {
    overflow-y: auto;
    height: 523px;
}

The Content inside the div section is dynamic. div部分内的内容是动态的。 How to detect the end of the scroll position so that the API call happens once it reaches the end and append it to the previous content similar to the demo example in https://www.npmjs.com/package/react-infinite-scroller ?But in the example it is happening for window scroll, which is not what I need. 如何检测滚动位置的结束,以便API调用在到达结尾时发生,并将其附加到以前的内容,类似于https://www.npmjs.com/package/react-infinite-scroller中的演示示例?但是在示例中它正在发生窗口滚动,这不是我需要的。 It should happen only for the div scroll. 它应该只发生div滚动。

If you want to try and do this yourself, you can attempt to do it like this. 如果您想尝试自己尝试,可以尝试这样做。 Attach a ref to the div in question, and then in your componentDidMount attach an event listener of scroll to the div. 将一个引用附加到有问题的div,然后在componentDidMount附加一个滚动到div的事件监听器。 In the method where you handle the scroll event, you can get the div's scrollTop which you can then use to determine if more data should be requested. 在处理滚动事件的方法中,您可以获取div的scrollTop ,然后您可以使用它来确定是否应该请求更多数据。 Of course this is just a basic idea, and will require some more detail to get it working, but it should get you started. 当然这只是一个基本的想法,并且需要更多的细节来使它工作,但它应该让你开始。

Here is some sample code. 这是一些示例代码。

 componentDidMount() {
    this.div.addEventListener("scroll", this.handleScroll);
  }

  handleScroll = e => {
    console.log(this.div.scrollTop);
  };

  render() {
    const style = {
      height: 400,
      width: 400,
      overflow: "auto"
    };
    return (
      <div ref={div => (this.div = div)} style={style}>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>Hello</h1>
        <h1>world</h1>
        <h1>world</h1>
        <h1>world</h1>
        <h1>world</h1>
        <h1>world</h1>
      </div>
    );
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM