Listen for scroll up / down?

前端 未结 2 2097
终归单人心
终归单人心 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:29

    Actually there are many ways to do it, but using React hooks was the easier one for me, all you need to do is:

    • define a state for scroll position
    • a function to update your scroll position state
    • start a scroll listen when component mounts
    • stop the listen when component unmount

    Something like:

    import React, { useState, useEffect } from 'react';
    
    ...
    // inside component:
    
    const [scrollPosition, setSrollPosition] = useState(0);
    const handleScroll = () => {
        const position = window.pageYOffset;
        setSrollPosition(position);
    };
    
    useEffect(() => {
        window.addEventListener('scroll', handleScroll, { passive: true });
    
        return () => {
            window.removeEventListener('scroll', handleScroll);
        };
    }, []);
    

    Now you have scrollPosition in pixels to work on

    In this particular case useEffect will be equivalent to componentDidMount because it will be fired once the component mounts, but also after all updates, but addEventListener is smart enough to not start duplicated listeners.

    The return inside of useEffect is equivalent to componentWillUnmount, it'll "called" when the component unmounts.

    0 讨论(0)
  • 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
      }
    }
    
    0 讨论(0)
提交回复
热议问题