Listen for scroll up / down?

前端 未结 2 2098
终归单人心
终归单人心 2021-02-07 10:28

I\'m building an app (ES6) and I\'m curious what is the \'correct\' way to catch scroll up / down events?

I tried (npm) installing react-scroll-listener but I couldn\'t

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-07 11:30

    This is general advice for hooking into any listeners:

    Attach stuff in componentDidMount, unattach in componentWillUnmount

    class Whatever extends Component {
      componentDidMount() {
        window.addEventListener('scroll', this.handleScroll, { passive: true })
      }
    
      componentWillUnmount() {
        window.removeEventListener('scroll', this.handleScroll)
      }
    
      handleScroll(event) {
        // do something like call `this.setState`
        // access window.scrollY etc
      }
    }
    

提交回复
热议问题