React图片懒加载

大家好,又见面了,我是你们的朋友全栈君。

React图片懒加载
  • 话不多说了,创建一个LazyLoad.js的React组件,然后将下面的代码复制过去:
import React from 'react'
// import './lazyload.css'
// threshold
const threshold = [0.01]
class LazyLoad extends React.Component{ 
   
    constructor(props){ 
   
        super(props)
        this.state = { 
   
            io: null,
            refs: null,
            images: null,
            loading: true
        }
        this.handleonload = this.handleonload.bind(this)
    }
    UNSAFE_componentWillMount(){ 
   
        var { 
   ImgClassName, src, alt, ImgStyle } = this.props.state
        ImgClassName = ImgClassName ? ImgClassName : 'lazyload-img'
        alt = alt ? alt : 'antd-lazyload'
        var images = []
        var refs = []
        const ref = React.createRef()
        refs.push(ref)
        images.push(
            <img className={ 
   ImgClassName} ref={ 
   ref} data-src={ 
   src} alt={ 
   alt} style={ 
   { 
   ...ImgStyle}} />
        )
        this.setState({ 
   
            refs,
            images
        })
    }
    componentDidMount(){ 
   
        const io = new IntersectionObserver(entries=>{ 
   
            entries.forEach(item=>{ 
   
                if(item.intersectionRatio <= 0) return
                var { 
    src } = this.props.state
                const { 
    target } = item
                var image = new Image()
                image.src = src
                image.onload = ()=>{ 
   
                    this.setState({ 
    loading: false })
                    target.src = target.dataset.src
                }
            })
        },{ 
   
            threshold
        })
        this.setState({ 
    io })
    }
    handleonload(){ 
   
        var { 
    io, refs } = this.state
        refs.forEach(item=>{ 
   
            io.observe(item.current)
        })
    }
    render(){ 
   
        var { 
    BoxClassName, width, height, BoxStyle } = this.props.state
        BoxClassName = BoxClassName ? BoxClassName : 'lazyload-img-box'
        var { 
    images } = this.state
        return (
            <div className={ 
   BoxClassName} style={ 
   { 
   width, height, ...BoxStyle}}>
                { 
   images}
                <img onError={ 
   this.handleonload} src='' alt='antd-lazyload' style={ 
   { 
   display: 'none'}} />
            </div>
        )
    }
}
export default LazyLoad
  • 使用的时候,像这样:
<LazyLoad 
	state={ 
   { 
   
		src: 'http://example.com/1.jpg',
		alt; '1.jpg',
		BoxClassName: 'lazyload-box', // 这是容器的类名
		ImgClassName: 'lazyload-img' // 这是img的类名
	}}
></LazyLoad>
  • 想知道更多使用请点击这里

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/125903.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022年4月6,如有侵权请联系 cloudcommunity@tencent.com 删除

posted on 2024-04-02 11:30  漫思  阅读(13)  评论(0编辑  收藏  举报

导航