addEventListeners and React not working as planned

对着背影说爱祢 提交于 2021-01-01 06:45:52

问题


I try to make a timeline that is dynamicaly loaded when scrolling. Due to this I need the scroll event, combined with React.

window.addEventListener("scroll", console.log('scroll'), true);

This should console log a scroll every time I scroll, but it just log it once, then nothing

EDIT:

If I use it in my real application now, with this code :

callbackFunc = () => {
        for (var i = 0; i < items.length; i++) {
            if (this.isElementInViewport(items[i])) {
                items[i].classList.add("in-view");
            }
        }
    }

componentDidMount() {
        window.addEventListener("load", function (event) { this.callbackFunc(); }, true);
        window.addEventListener("resize", function (event) { this.callbackFunc(); }, true);
        window.addEventListener("scroll", function (event) { this.callbackFunc(); }, true)
    }

It says callbackFunc is not a function


回答1:


This isn't working because the event listener expects a function as it's second argument (or an object implementing the EventListner interface) which it will call when the "scroll" occurs. console.log is a function, but console.log("scroll") isn't a function, its a called function. And so the value you are technically putting as the second argument is undefined (as console.log("scroll") returns undefined).

const a = console.log("scroll");
console.log(a); // undefined (the value of your second arugment)

So, you need to wrap the console.log() in a function, so the function is called, which will then call your console.log() method. You can achieve this by using an ES6 arrow function:

window.addEventListener("scroll", _ => console.log('scroll'), true);

window.addEventListener("scroll", _ => console.log('scroll'), true);
body {
  height: 200vh;
}

As per your edit, the arrow function should solve your issue. Currently, the window is calling your event listener function, so this is referring to the window, not the context of your app. Using an arrow function should fix this (as an arrow function doesn't have it's own this).




回答2:


Try this:

window.addEventListener("scroll", function(event) { console.log('scroll'); }, true);



回答3:


Try adding it in reactjs

 componentDidMount() lifecycle function


来源:https://stackoverflow.com/questions/54388142/addeventlisteners-and-react-not-working-as-planned

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