在React中使用H5接口IntersectionObserver實現圖片懶加載

export let picLazyLoad = function(){
    let observer = new IntersectionObserver(
        (changes) => {
            changes.forEach((change) => {
                if(change.intersectionRatio > 0){
                    console.log(change.target)
                    var img = change.target;
                    img.src = img.dataset.src;
                    observer.unobserve(img);
                }
            })
        }
    )
    Array.from(document.getElementsByClassName('cover')).forEach((item) => {
        observer.observe(item);
    })
}

將此方法導出,以便在不同的組件中可以使用。

componentDidMount = () => {
        let self = this
        this.context.getYoutubeData(picLazyLoad)
    }

之後在componentDidMount生命週期中,獲取數據之後的回調中去調用該方法。此處一定要在頁面渲染之後再調用方法,否則獲取不到target。該方法的缺點是兼容性不高,兼容性如下圖:

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章