React图片懒加载
话不多说了,创建一个LazyLoad.js的React组件,然后将下面的代码复制过去:import React from 'react'// import './lazyload.css'// thresholdconst threshold = [0.01]class LazyLoad extends ponent{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.stateImgClassName = 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) returnvar {src } = this.props.stateconst {target } = itemvar image = new Image()image.src = srcimage.onload = ()=>{this.setState({loading: false })target.src = target.dataset.src}})},{threshold})this.setState({io })}handleonload(){var {io, refs } = this.staterefs.forEach(item=>{io.observe(item.current)})}render(){var {BoxClassName, width, height, BoxStyle } = this.props.stateBoxClassName = BoxClassName ? BoxClassName : 'lazyload-img-box'var {images } = this.statereturn (<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: '/1.jpg',alt; '1.jpg',BoxClassName: 'lazyload-box', // 这是容器的类名ImgClassName: 'lazyload-img' // 这是img的类名}}></LazyLoad>
想知道更多使用请点击这里