一、问题描述
antd 中下拉框组件Select 在渲染1000条级别的数据时会导致卡顿
解决方案: **思路:**采用分页的形式,通过计算滚动条触底时更新下一页数据;
import { Select } from 'antd';
import React, { useEffect, useState } from 'react';
const { Option } = Select;
export default function learn6() {
const [data, setdata] = useState([]);
const [selectData, setselectData] = useState({
pageSize: 100,
pageNum: 1,
data: []
});
useEffect(() => {
const arr: any = [];
for (let i = 0; i < 1000; i++) {
arr.push(i);
}
setdata(arr);
setselectData((pre) => ({
...pre,
data: arr.slice(0, 100)
}));
}, []);
const onPopupScrollHandle = (event: any) => {
const scrollTop = event.target.scrollTop;
const scrollHeight = event.target.scrollHeight;
const clientHeight = event.target.clientHeight;
if (scrollHeight - scrollTop <= clientHeight) {
console.log('滚动条到底部了');
setselectData((pre) => ({
...pre,
pageNum: pre.pageNum + 1,
data: [
...pre.data,
...data.slice(
pre.pageNum * pre.pageSize,
(pre.pageNum + 1) * pre.pageSize
)
]
}));
}
};
return (
<div>
<Select
style={{ width: 200 }}
onPopupScroll={onPopupScrollHandle}
placeholder="请选择"
>
{selectData.data.map((item) => {
return (
<Option key={item} value={item}>
{item}
</Option>
);
})}
</Select>
</div>
);
}
|