100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > React图片懒加载

React图片懒加载

时间:2021-10-08 17:08:52

相关推荐

React图片懒加载

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>

想知道更多使用请点击这里

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。