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

相关推荐
我不吃饼干15 小时前
TypeScript 类型体操练习笔记(二)
前端·typescript
光影少年15 小时前
浏览器渲染原理?
前端·javascript·前端框架
小白探索世界欧耶!~15 小时前
Vue2项目引入sortablejs实现表格行拖曳排序
前端·javascript·vue.js·经验分享·elementui·html·echarts
GISer_Jing17 小时前
前端营销(AIGC II)
前端·react.js·aigc
漠月瑾-西安17 小时前
React-Redux Connect 高阶组件:从“桥梁”到“智能管家”的深度解析
react.js·设计模式·react-redux·高阶组件·connect高阶租单间·原理理解
NEXT0617 小时前
深度解析 JWT:从 RFC 原理到 NestJS 实战与架构权衡
前端·typescript·nestjs
程序员林北北18 小时前
【前端进阶之旅】节流与防抖:前端性能优化的“安全带”与“稳定器”
前端·javascript·vue.js·react.js·typescript
寻星探路19 小时前
【前端基础】HTML + CSS + JavaScript 快速入门(三):JS 与 jQuery 实战
java·前端·javascript·css·c++·ai·html
未来之窗软件服务20 小时前
未来之窗昭和仙君(六十九)前端收银台行为异常检测—东方仙盟练气
前端·仙盟创梦ide·东方仙盟·昭和仙君
大叔编程奋斗记20 小时前
两个日期间的相隔年月计算
前端·salesforce