Detecting scrolling direction on the page - updating prev value

本秂侑毒 提交于 2021-01-21 06:07:56

问题


I'm using React and I need to get a scroll direction in order to do some stuff. I have a working code but I'm clueless on how to store and update previous scroll position.

Here's my code:

componentDidMount(){
    const prev = window.scrollY;
    window.addEventListener('scroll', e => this.handleNavigation(e, prev);
}

Visible problem here is that componentDidMount fires only once so when I try to do the following:

handleNavigation = (e, prev) =>{
    const window = e.currentTarget;

    if(prev > window.scrollY){
        console.log("scrolling up");
    }
    else if(prev < window.scrollY){
        console.log("scrolling down");
    }
};

It compares values properly but prev never changes, so it doesn't work as intended. How do I make it work?

Do I put prev inside the interval to update the value or something crazy like that?


回答1:


Try the following. It should work since this way the previous value is stored in the instance of the component.

componentDidMount() {
    this.prev = window.scrollY;
    window.addEventListener('scroll', e => this.handleNavigation(e));
}

handleNavigation = (e) => {
    const window = e.currentTarget;

    if (this.prev > window.scrollY) {
        console.log("scrolling up");
    } else if (this.prev < window.scrollY) {
        console.log("scrolling down");
    }
    this.prev = window.scrollY;
};


来源:https://stackoverflow.com/questions/50412259/detecting-scrolling-direction-on-the-page-updating-prev-value

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