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

相关推荐
溪语流沙几秒前
【每天一个CSS | Day08】整排按钮被鼠标吸走的磁吸导航
前端·css·计算机外设
就叫年华吧丶10 分钟前
长文档点目录定位总是不准?一个 content-visibility + 平滑滚动引发的连环坑(Vue3 实战)
前端·javascript·算法·vue
JudithHuang16 分钟前
React 路由:React Router
前端·react.js·前端框架
赵得C18 分钟前
创建 SVG 图标预览页面:从零实现到解决 CORS 问题
前端·javascript·html
IT_陈寒24 分钟前
Java的HashMap线程安全问题让我深夜掉光了头发
前端·人工智能·后端
三掌柜66628 分钟前
ArkWeb 手记 04|Web 返回键别再一刀切
前端·harmonyos
光影少年33 分钟前
RN与Flutter架构区别
前端·flutter·react native·react.js·架构·node.js
peter676840 分钟前
css学习小结
前端·css·学习
liangshanbo121541 分钟前
什么是CSS原子化?它的优劣势是什么?
前端·css·tensorflow·css原子化
.道阻且长.43 分钟前
C++ 11:可变参数模板
前端·c++·算法