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(){