检测页面上的滚动方向-更新上一个值 [英] Detecting scrolling direction on the page - updating prev value

查看:49
本文介绍了检测页面上的滚动方向-更新上一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React,我需要获取滚动方向才能做一些事情.我有一个有效的代码,但是对如何存储和更新以前的滚动位置一无所知.

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.

这是我的代码:

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

这里可见的问题是componentDidMount 仅触发一次,因此当我尝试执行以下操作时:

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?

我是否将prev放在时间间隔内以更新值或类似的东西?

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

推荐答案

请尝试以下操作.之所以应该工作,是因为这种方式将先前的值存储在组件的实例中.

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

这篇关于检测页面上的滚动方向-更新上一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆