在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。该方法的缺点是兼容性不高,兼容性如下图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43170484/article/details/87877940
今日推荐