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 是 判断是否还有数据状态

相关推荐
丷丩4 小时前
MapLibre GL JS第41课:向地图添加图标
前端·javascript·mapbox·maplibre gl js
英俊潇洒美少年4 小时前
前端性能优化:非关键脚本/第三方资源异步加载全解(彻底解决首屏阻塞)
前端·性能优化
JieE2124 小时前
Bun + TypeScript:下一代 JavaScript 全栈开发的正确打开方式
typescript·全栈·bun
开飞机的舒克_4 小时前
vue3+router动态权限路由
前端·vue.js
VitoChang4 小时前
放弃手搓路由吧!用 SolidStart 搞 SPA,真香
前端
GuWenyue4 小时前
告别JS类型坑!Ts为什么在ai时代逐渐成为"第一"语言
前端·算法·typescript
三乐2284 小时前
事件循环是什么东西,一篇文章带你了解
前端·javascript
wuhen_n4 小时前
RAG 核心:向量嵌入与本地向量数据库实战
前端·langchain·ai编程
孟陬4 小时前
国外技术周刊 #139:LLM 正在杀死程序员的「懒惰美德」
前端·人工智能·后端
lichenyang4534 小时前
补充:Repeat 虚拟滚动与 cachedCount 到底怎么用
前端