React图片懒加载
页面新建js文件 写入一下代码
LazyLoad.js
import React from 'react'
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, datasrc } = this.props.state
ImgClassName = ImgClassName ? ImgClassName : 'lazyload-img'
alt = alt ? alt : ''
var images = []
var refs = []
const ref = React.createRef()
refs.push(ref)
images.push(
<img className={ImgClassName} ref={ref} data-src={datasrc} src={src} alt={alt} style={{ ...ImgStyle }} key='src' />
)
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='' style={{ display: 'none' }} />
</div>
)
}
}
export default LazyLoad
页面使用把LazyLoad.js文件引入组件中
import React, { Component } from 'react';
import LazyLoad from './components/LazyLoad';
class App extends Component {
constructor(...args) {
super(...args);
}
render() {
return (
<div className="load-more-left">
<LazyLoad
state={{
src: `http://www.ibugthree.com/default.gif`, //默认显示的图片
datasrc: 'http://www.ibugthree.com/detail_img/BM/BM10.jpg',//这个是渲染的图片这个可以动态渲染出来
BoxClassName: 'load-more-kmr', // 这是容器的类名
ImgClassName: 'load-more-kmr' // 这是img的类名
}}
></LazyLoad>
</div>
)
}
}
export default App;
这样就实现了图片懒加载的效果