React图片懒加载组件实现

640#ee8a58cf

做一个项目,使用ant组件库,人家没有提供图片懒加载组件,自己花了几分钟做了个,提供参考,欢迎留言优化建议。

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

自行优化。◕‿◕。

参与本文讨论

请先登录 GitHub 后留言

0/500

本文留言

0

这篇文章还没有留言,来写第一条吧。

1 / 1