移动端加载更多组件

57 阅读1分钟

前言

移动端分页列表组件中,需要用到 加载更多 组件,下面我们简单来进行介绍。

react实现

import React, { ReactElement, useState } from 'react'

interface ILoadMoreProps {
    children: ReactElement | ReactElement[]
    options?: {
        className?: string
        offset?: number // 滚定到距离底部还有多少距离触发加载更多回调
    }
    onLoadMore?: () => void // 加载更多回调
}

let tk
const delay = 300
export const LoadMore: React.FC<ILoadMoreProps> = props => {
    const { options = {}, onLoadMore } = props
    const { offset = 1, className, styleName = {} } = options
    const [preScrollTop, setPreScrollTop] = useState(0)

    const handleScroll = e => {
        const scrollTop = e.target.scrollTop
        const scrollHeight = e.target.scrollHeight
        const clientHeight = e.target.clientHeight
        const isScrollUp = scrollTop - preScrollTop > 0
        // 记录scrollTop值,判断滚动方向
        setPreScrollTop(preScrollTop)
        // 是否滑动到底部
        if (isScrollUp && offset + scrollTop + clientHeight >= scrollHeight) {
            if (!tk) {
                onLoadMore?.()
            }
            tk = setTimeout(() => {
                clearTimeout(tk)
                tk = null
            }, delay)
        }
    }

    return (
        <div className={className} style={{ ...styleName }} onScroll={handleScroll}>
            {props.children}
        </div>
    )
}

export default LoadMore

参考:

手撸一个InfiniteScroll无限滚动加载组件