当前位置:网站首页>实现下拉加载更多

实现下拉加载更多

2022-08-09 10:03:00 高桥靓仔

import React, { useState, useEffect } from 'react'
import produce from "immer"
import { Select } from 'antd'
const { Option } = Select

const SelectAntd = () => {
    const data = [//源数据
        1, 2, 3, 4, 5,
        6, 7, 8, 9, 10,
        11, 12, 13, 14, 15,
        16, 17, 18, 19, 20,
        21, 22, 23, 24, 25,
        26, 27, 28, 29, 30,
        31, 32, 33, 34, 35,
        36, 37, 38
    ]
    const [lazyData, setLazyData] = useState([])
    const [count, setCount] = useState(1)
    const [pageData, setPageData] = useState([])
    useEffect(() => {//初始化需要懒加载的数据可以滑动
        setLazyData(pageData[0])
        
    }, [pageData])
    useEffect(() => {
        setPageData(paging(data, 10))
    },[])

    const optionRender = () => {//渲染option
        return lazyData?.map(i => (
            <Option value={i} key={i}>{i}</Option>
        ))
    }

    const handleScroll = (e) => {//判断滑动到底部
        const { scrollTop, scrollHeight, clientHeight } = e.target
        return scrollHeight - scrollTop === clientHeight
    }

    const paging = (sourceData, pageSize) => {//页量
        const pageNum = Math.ceil(sourceData.length / pageSize)//页数
        return new Array(pageNum).fill([]).map((item, index) => (
            sourceData.slice(index * pageSize, (index + 1) * pageSize)
        ))
    }

    // const pageData = paging(data, 10)//分页后的元组

    const lazyLoad = (e) => {//触发懒加载
        if (handleScroll(e) && pageData[count]) {
            setLazyData(produce(lazyData, daft => {
                daft = daft.push(...pageData[count])
            }))
            setCount(count + 1)
        }
    }

    return (
        <Select
            showSearch
            style={
   { width: 200 }}
            placeholder="Select a person"
            onPopupScroll={(e) => { lazyLoad(e) }}//滚动时触发
        >
            {optionRender()}
        </Select>
    )

}
export default SelectAntd

实现下拉到底部,懒加载的效果:

在这里插入图片描述

原网站

版权声明
本文为[高桥靓仔]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_45221036/article/details/109066258