react ts实现一个 无限加载组件

页面滑动到底部,直接加载下一页数据

  • InfiniteScroll.tsx

    /**

    • 无限 加载组件
      */

    import { FC, createRef, useEffect, CSSProperties } from 'react'
    import LoadingText from '../LoadingText'

    type PropsType = {
    loadMore: () => void
    hasMore: boolean
    }

    const InfiniteScroll: FC = (props: PropsType) => {
    const { loadMore, hasMore } = props
    // const [loading, setLoading] = useState(hasMore)
    const ref = createRef()
    // console.log('InfiniteScroll', hasMore)

    复制代码
    useEffect(() => {
      const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            // setLoading(false)
            loadMore()
          }
        })
      })
      // console.log('ref.current', ref.current)
    
      if (ref.current) {
        observer.observe(ref.current)
      }
    }, [])
    
    const defaultStyle: CSSProperties = {
      padding: '0 0 0.6rem 0'
    }
    
    return (
      <div className="scroll-load-more" ref={ref}>
        {hasMore ? (
          <LoadingText defaultStyle={defaultStyle} />
        ) : (
          <LoadingText>
            <div
              style={{
                ...defaultStyle,
                textAlign: 'center',
                fontSize: '0.28rem',
                color: '#999'
              }}
            >
              --- 我是有底线的 ---
            </div>
          </LoadingText>
        )}
      </div>
    )

    }

    export default InfiniteScroll

  • 用法

    ....

    复制代码
    async function loadMore() {
      // 加载下一页数据
    }

    // hasMore 是 判断是否还有数据状态

相关推荐
前端不太难7 分钟前
Edge AI 时代:从数据中心到终端,算力如何无处不在?
前端·人工智能·edge
Highcharts.js8 分钟前
Highcharts v13 全新时间轴标签边界格式|让时间维度表达更智能
前端·信息可视化·时间序列·图表开发·chart·自定义标签·可视化开发
lichenyang4539 分钟前
鸿蒙研读 10:@Provider/@Consumer、RelativeContainer、onNewWant
前端
大湿兄啊啊啊14 分钟前
MID360S调试
java·服务器·前端
绺年16 分钟前
模块化加载机制与循环依赖的探索
前端
Csvn25 分钟前
前端技术 - 前端技术债务
前端
Days205035 分钟前
Flyfish Viewer:全能纯前端多格式文件预览组件,解锁浏览器端无门槛预览新体验
前端
selfsuer36 分钟前
【奇奇怪怪前端问题记录】
前端
不要额外加糖39 分钟前
给 Codex 戴上紧箍, 治一治 AI 的过度发挥
前端·人工智能·代码规范