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

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

  • InfiniteScroll.tsx

    /**

    • 无限 加载组件
      */

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

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

    const InfiniteScroll: FC<PropsType> = (props: PropsType) => {
    const { loadMore, hasMore } = props
    // const [loading, setLoading] = useState(hasMore)
    const ref = createRef<HTMLDivElement>()
    // 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

  • 用法

    ....
    <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />

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

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

相关推荐
若惜6 小时前
selenium自动化测试web自动化测试 框架封装Pom
前端·python·selenium
Amumu121386 小时前
Js:内置对象
开发语言·前端·javascript
广州华水科技6 小时前
2026年单北斗GNSS变形监测系统推荐,助力精准监控与智慧城市建设
前端
鸡吃丸子6 小时前
如何编写一个高质量的AI Skill
前端·ai
我命由我123457 小时前
Element Plus 2.2.27 的单选框 Radio 组件,选中一个选项后,全部选项都变为选中状态
开发语言·前端·javascript·html·ecmascript·html5·js
Luna-player7 小时前
第3章 Spring Boot的Web应用支持,个人学习笔记
前端·spring boot·学习
bugcome_com7 小时前
【ASP.NET Web Pages】页面布局核心实战:从复用性到安全性,打造一致化网站界面
前端·后端·asp.net
Sylus_sui7 小时前
Class 模型 + 跨组件状态(@Observed)+ 网络请求封装 + 本地存储全部是鸿蒙 Next/Stage 模型标准写法
前端
代码栈上的思考7 小时前
消息队列持久化:文件存储设计与实现全解析
java·前端·算法
踩着两条虫7 小时前
去“AI味儿”实操手册:从“机器脸”到“高级脸”,只差这三步!
前端·vue.js·ai编程