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

相关推荐
决斗小饼干1 天前
低代码平台工作流引擎设计:从状态机到智能流转的技术演进
前端·低代码·工作流引擎
豆苗学前端1 天前
彻底讲透浏览器缓存机制,吊打面试官
前端·javascript·面试
米丘1 天前
了解 window.history 和 window.location, 更好地掌握 vue-router、react-router单页面路由
前端
swipe1 天前
箭头函数与 this 面试题深度解析:从原理到实战
前端·javascript·面试
星_离1 天前
《Vue 自定义指令注册技巧:从手动到自动,效率翻倍》
前端·vue.js
狗头大军之江苏分军1 天前
消耗 760万 Token 后,一文看懂了“小龙虾” OpenClaw 和 OpenCode 的区别
前端·后端
毛骗导演1 天前
万字解析 OpenClaw 源码架构-安全与权限
前端·架构
哇哇哇哇1 天前
vue3 ref解析
前端
哇哇哇哇1 天前
vue3 reactive解析
前端
光影少年1 天前
Vue的响应式原理?Vue2和Vue3有什么区别?
前端·vue.js·掘金·金石计划