Detecting when user scrolls to bottom of div with React js

后端 未结 9 2199
悲哀的现实
悲哀的现实 2020-11-28 21:17

I have a website with different sections. I am using segment.io to track different actions on the page. How can I detect if a user has scrolled to the bottom of a div? I hav

9条回答
  •  抹茶落季
    2020-11-28 21:44

    Add following functions in your React.Component and you're done :]

      componentDidMount() {
        window.addEventListener("scroll", this.onScroll, false);
      }
    
      componentWillUnmount() {
        window.removeEventListener("scroll", this.onScroll, false);
      }
    
      onScroll = () => {
        if (this.hasReachedBottom()) {
          this.props.onScrollToBottom();
        }
      };
    
      hasReachedBottom() {
        return (
          document.body.offsetHeight + document.body.scrollTop ===
          document.body.scrollHeight
        );
      }
    

提交回复
热议问题