简体   繁体   中英

ReactJS - detect when the vertical scroll appears

I would like to do some action when a vertical window's browser scroll appears. like this image below:

https://www.dropbox.com/s/t8th7cp7rcr662a/scroll.jpg?dl=0

This code below didn't work.

class App extends Component {
      constructor(props) {
        super(props)      
        this.onScroll = this.onScroll.bind(this)
      }

      onScroll(){
        window.onscroll = function (Event) {
          alert('the scroll is visible!')
        }
      }

      componentDidMount() {      
        window.addEventListener('onscroll', this.onScroll)
      }

      componentWillUnmount() {         
        window.removeEventListener('onscroll', this.onScroll)
      }

      render() {
        return (
          <div>
            <canvas id="canvas"></canvas>
            <div className="wrapper-all">
              <Coluna1 />
              <Coluna2 />
              <FooterMobile />
            </div>

          </div>
        )
      }
    }


    export default App;

您可以侦听resize事件,并将document.body.scrollHeightdocument.body.clientHeight进行比较。

componentDidMount() {
    const screenHeight = window.innerHeight;
    const totalHeight = window.body.scrollHeight;

    if(screenHeight < totalHeight) {
        alert('Scroll detected');
    }

}

This code will most probably solve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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