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
自行优化。◕‿◕。