React图片懒加载组件实现
AsyncImage.tsx
js
import * as React from 'react'
export interface AsyncImageProps {
// 图片地址
dataSrc: string
// 说明
alt?: string
}
export interface AsyncImageState {
show: boolean
}
class AsyncImage extends React.Component<AsyncImageProps, AsyncImageState> {
private imgRefs: any
constructor(props: AsyncImageProps) {
super(props)
this.state = { show: false }
this.imgRefs = React.createRef()
}
componentDidMount() {
// 判断是否在可视区域内
const isHidden = (): boolean => {
// 滚动高度
const scrollTop =
document.documentElement.scrollTop || document.body.scrollTop
// 可视区域高度
const clientHeight = document.documentElement.clientHeight
return this.imgRefs.current.offsetTop > scrollTop + clientHeight
}
// 首先计算位置
if (!isHidden()) {
this.setState({
show: true
})
return null
}
// scroll事件
const scrollEvent = () => {
if (!isHidden()) {
this.setState(
{
show: true
},
() => {
window.removeEventListener('scroll', scrollEvent)
}
)
}
}
window.addEventListener('scroll', scrollEvent)
}
render() {
return (
<React.Fragment>
{this.state.show ? (
<img src={this.props.dataSrc} alt={this.props.alt} />
) : (
<div ref={this.imgRefs} data-src={this.props.dataSrc}></div>
)}
</React.Fragment>
)
}
}
export default AsyncImage
自行优化。◕‿◕。
![[微笑]](/face/0.gif)
![[嘻嘻]](/face/1.gif)
![[哈哈]](/face/2.gif)
![[可爱]](/face/3.gif)
![[可怜]](/face/4.gif)
![[挖鼻]](/face/5.gif)
![[吃惊]](/face/6.gif)
![[害羞]](/face/7.gif)
![[挤眼]](/face/8.gif)
![[闭嘴]](/face/9.gif)
![[鄙视]](/face/10.gif)
![[爱你]](/face/11.gif)
![[泪]](/face/12.gif)
![[偷笑]](/face/13.gif)
![[亲亲]](/face/14.gif)
![[生病]](/face/15.gif)
![[太开心]](/face/16.gif)
![[白眼]](/face/17.gif)
![[右哼哼]](/face/18.gif)
![[左哼哼]](/face/19.gif)
![[嘘]](/face/20.gif)
![[衰]](/face/21.gif)
![[委屈]](/face/22.gif)
![[吐]](/face/23.gif)
![[哈欠]](/face/24.gif)
![[抱抱]](/face/25.gif)
![[怒]](/face/26.gif)
![[疑问]](/face/27.gif)
![[馋嘴]](/face/28.gif)
![[拜拜]](/face/29.gif)
![[思考]](/face/30.gif)
![[汗]](/face/31.gif)
![[困]](/face/32.gif)
![[睡]](/face/33.gif)
![[钱]](/face/34.gif)
![[失望]](/face/35.gif)
![[酷]](/face/36.gif)
![[色]](/face/37.gif)
![[哼]](/face/38.gif)
![[鼓掌]](/face/39.gif)
![[晕]](/face/40.gif)
![[悲伤]](/face/41.gif)
![[抓狂]](/face/42.gif)
![[黑线]](/face/43.gif)
![[阴险]](/face/44.gif)
![[怒骂]](/face/45.gif)
![[互粉]](/face/46.gif)
![[心]](/face/47.gif)
![[伤心]](/face/48.gif)
![[猪头]](/face/49.gif)
![[熊猫]](/face/50.gif)
![[兔子]](/face/51.gif)
![[ok]](/face/52.gif)
![[耶]](/face/53.gif)
![[good]](/face/54.gif)
![[NO]](/face/55.gif)
![[赞]](/face/56.gif)
![[来]](/face/57.gif)
![[弱]](/face/58.gif)
![[草泥马]](/face/59.gif)
![[神马]](/face/60.gif)
![[囧]](/face/61.gif)
![[浮云]](/face/62.gif)
![[给力]](/face/63.gif)
![[围观]](/face/64.gif)
![[威武]](/face/65.gif)
![[奥特曼]](/face/66.gif)
![[礼物]](/face/67.gif)
![[钟]](/face/68.gif)
![[话筒]](/face/69.gif)
![[蜡烛]](/face/70.gif)
![[蛋糕]](/face/71.gif)