React 监听浏览器onscroll事件

#1

求助啊,我需要浏览器中监听onscroll事件,我用的mac,上下滚动网页的话一直触发不了scroll事件,如果再触摸板上用俩手指对网页进行缩放就触发scroll事件了,进入handleScroll了。我是这么写的,谁知道为什么啊

  componentDidMount: function () {
     window.addEventListener('scroll', this.handleScroll);
  },
  componentWillUnmount: function () {
    window.removeEventListener('scroll', this.handleScroll);
  },
  handleScroll: function (e) {
    console.log('浏览器滚动事件')
  },
#2

不对, scroll 是不冒泡的. 要绑在节点上才行.

#3

可是为什么我用原生的js写法,就没有问题。didMount 之后我应该是可以操作实际dom的。
这是原生的写法

window.addEventListener('scroll', function () {
    var obj = document.getElementById('test');
    console.log(obj.offsetTop - document.body.scrollTop);
    if (obj.offsetTop - document.body.scrollTop <= 0) {
      obj.style.position = 'fixed';
      obj.style.top = '-20px';
    }
  })
后来我没用window取的body的.在componentDidMount里面这么写的
    $('body').scroll(this.handleScroll);
仍然监听不到scroll事件。。。。
#4

window 对象大概有点特殊, 这个情况我也不清楚问题在哪了

#5

this…看看 this 的 上下文环境!

#6
 componentDidMount() {
    window.addEventListener('scroll', this.handleScroll.bind(this));
  }
  componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll.bind(this));
  }
  handleScroll(e) {
    console.log('浏览器滚动事件');
  }
#7

当运行这个语句的时候,你认为 this 指向的是当前的组件,而实际上 this 指向的是 window 对象。:smirk:

#8

我的做法是除了你写的添加‘scroll’事件外,在handleScroll事件里还需要利用ref获取dom节点,监听这个节点,可以实现。 不能监听body哦。还有这样做,在移动端屏幕滚动时是无法触发的,得停止滚动才会触发监听。 还请高人完美解决react滚动事件。

#9

进入其他页面,在返回时,会出现:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
#10

你认为 this 指向的 window 对象,而实际上 this 指向的是当前组件。

#11

不知道这么久了,lz解决没?
我试了下你的代码,一切正常啊,正常触发scroll。不过可以考虑下,你的div之类的有没有设置overflow scroll之类的。可能body的高度就是视口的高度,body不发生滚动的。body里面的div滚动了而已,scroll没冒泡。

#12

是这样的,为自己当初草率的回答感到惭愧:sweat:

#14

这个是错误回答:sweat:

2 Likes
#15

请问楼主最后是怎么解决这个问题的呢。。。

#16

这么写就对了

#17

可以看下我的回复,需要函数截流的话自己再加把

#18

OK, 蟹蟹٩(‘ω’)و楼主!笔芯ღ( ´・ᴗ・` )

#19

是的

在 chrome 中

只有后者有 值

#20
componentDidMount() {
        let _this = this;
        window.addEventListener('scroll', () => {
            _this.handleScroll();
        });
    }

这样写

#21

你好,关于this.function.bind(this),我感到困惑,能不能指点我一下,第一个this指向当前组件,第二个this指向当前组件创建的实例吗?