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

相关推荐
demi_meng3 小时前
reactNative 遇到的问题记录
javascript·react native·react.js
千码君20164 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
lijun_xiao20096 小时前
前端最新Vue2+Vue3基础入门到实战项目全套教程
前端
90后的晨仔6 小时前
Pinia 状态管理原理与实战全解析
前端·vue.js
杰克尼6 小时前
JavaWeb_p165部门管理
java·开发语言·前端
90后的晨仔6 小时前
Vue3 状态管理完全指南:从响应式 API 到 Pinia
前端·vue.js
90后的晨仔7 小时前
Vue 内置组件全解析:提升开发效率的五大神器
前端·vue.js
我胡为喜呀7 小时前
Vue3 中的 watch 和 watchEffect:如何优雅地监听数据变化
前端·javascript·vue.js
我登哥MVP7 小时前
Ajax 详解
java·前端·ajax·javaweb