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
实现下拉到底部,懒加载的效果: