簡體   English   中英

如何從ReactJS中的addEventListener調用函數?

[英]How call a function from addEventListener in ReactJS?

我在ReactJS中做無限滾動,但遇到麻煩了!

加載組件后,執行以下操作:

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

而且,作為一種魔術,我沒有定義“ loadPhotos()”。 我不能使用this.loadPhotos(),因為它引用的是窗口(沒有loadPhotos())。

我在Constructor()方法中初始化loadPhotos():

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

我的loadPhotos()是在Constructor()方法之外定義的,我的意思是在類主體中定義。

有人可以幫我嗎? 感謝大伙們!

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

使用箭頭函數作為回調,這將引用組件的實例。

因為回調中的原始this引用了window ,所以您還需要將this.innerHeight更改為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
        }
    });
}

如果要使用自己的方式,則可以使用let _self = 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();
        }
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM