简体   繁体   中英

How call a function from addEventListener in ReactJS?

I'm doing an infinite scroll in ReactJS but I'm in trouble!

After my component loads, I do this:

componentDidMount() {
    window.addEventListener('scroll', function() {
        var h = this.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            loadPhotos();
        }
    });
}

and, as a magic, I've "loadPhotos() is not defined". I can't use this.loadPhotos() because it refers to window (that hasn't loadPhotos()).

I initialize my loadPhotos() in the constructor() method:

this.loadPhotos = this.loadPhotos.bind(this);

My loadPhotos() is defined outside the constructor() method, I mean that is defined in the class body.

Someone can help me? Thank you guys!

SOLUTION

componentDidMount() {
    window.addEventListener('scroll', () => { // arrow boys
        var h = window.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            this.loadPhotos();
        }
    });
}

Use an arrow function as the callback, and this will refer to the component's instance.

Because the original this inside the callback referred to window , you also need to change this.innerHeight to window.innerHeight .

componentDidMount() {
    window.addEventListener('scroll', () => { // arrow function
        var h = window.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            this.loadPhotos(); // now you can use this
        }
    });
}

If you want to use your way, You would fix issue by using let _self = this .

Like this

componentDidMount() {
    let _self = this;
    window.addEventListener('scroll', function() {
        var h = window.innerHeight;
        var j = document.documentElement.scrollHeight;
        var k = document.documentElement.scrollTop;
        if ((h + k) >= j - 150) {
            _self.loadPhotos();
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM