React—listen for scroll up / down?

半腔热情 提交于 2020-05-25 06:35:32

问题


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 get it to work with my ES6 class.

Basically I want: if scroll up, do this; if scroll down, do something else.

import React from 'react';
import config from '../config';
import StaticImageList from '../Common/StaticImageList';
import ScrollListener from 'react-scroll-listener';

class Album extends React.Component {
    constructor(props){
      super(props);

    }
    myScrollStartHandler(){
        console.log('Scroll start');

    }
    myScrollEndHandler(){
        console.log('Scroll end 300ms(default)');
    }
    componentDidMount(){
      scrollListener.addScrollHandler('body', myScrollStartHandler, myScrollEndHandler );
    }
    render(){
      return <StaticImageList />;
    }
};

export default Album; 

回答1:


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
  }
}



回答2:


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.



来源:https://stackoverflow.com/questions/38980371/react-listen-for-scroll-up-down

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!