ProFormSelect组件
最近在学习使用Ant Design Pro,在这里将遇到的问题罗列出来,方便后续学习,同样,如果你最近也在使用,希望能帮到你。
ProFormSelect支持滚动选择,如果数据过多,查找可能浪费时间,此时,我们可以使用自带的搜索功能,也可以自定义搜索。
<ProFormSelect
{...props}
mode={data.optionType === 1 ? 'single' : 'multiple'}
fieldProps={{
showSearch: true,
maxTagCount: 'responsive',
virtual: true,
onPopupScroll: e => handleScroll(e),
onSearch: handleSearchChange,
//这里可加入自定义加载动画
dropdownRender: menu => (
<>
{menu}
{loading && (
<div
style={{
width: '100%',
height: '50px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<Spin />
</div>
)}
</>
),
}}
options={dataQue}
/>
在这里,主要进行数据分页,也就是滚动加载,在里面有一个加载动画,当请求数据时展示
const [loading, setLoading] = useState(false);
const [dataSource, setDataSource] = useState<any>([]);
const [optionCurrent, setOptionCurrent] = useState(1);
const [hasMoreData, setHasMoreData] = useState(true);
const getNextPage = async () => {
if (!hasMoreData) {
return;
}
try {
const res = await getApiSetOps({
setId: data.setId,
optionCurrent,
optionPageSize: 10,
});
setLoading(true);
const newData: any = res.data;
setDataSource((prevData: any) => [...prevData, ...newData]);
setOptionCurrent(pre => (pre += 1));
if (newData[0].options.length === 0) {
setLoading(false);
setHasMoreData(false);
}
} catch (error) {
console.log(error);
} finally {
setLoading(false);
}
};
//监听滚动条
const handleScroll = (event: any) => {
const { scrollTop, scrollHeight, clientHeight } = event.target;
if (scrollHeight - (scrollTop + clientHeight) < 200) {
getNextPage();
}
};
useEffect(() => {
getNextPage();
}, []);
let dataQue = [];
if (dataSource && dataSource.length > 0) {
dataQue = dataSource.map((item: { options: { content: string; optionId: number }[] }) => {
const convertedOptions = item.options.map(option => {
const label = option.content.replace(/^[0-9]+##/, ''); // 删除 '#' 之前内容
const value = option.optionId;
return { label, value };
});
return { options: convertedOptions };
});
}
//防抖函数(搜索时使用)
const debounce = (func: { (value: any): void; apply?: any }, delay: number | undefined) => {
let timerId: string | number | NodeJS.Timeout | undefined;
return (...args: any) => {
clearTimeout(timerId);
timerId = setTimeout(() => {
// eslint-disable-next-line prefer-spread
func.apply(null, args);
}, delay);
};
};
const handleSearchChange = debounce((value: any) => {
const fn = async () => {
try {
const res = await getApiSetOps({ setId: data.setId, optionContent: value });
if (res.code === 0) {
const newData = res.data;
setDataSource((prevData: any) => {
const filteredData = newData.filter(
(item: any) => !prevData.some((prevItem: any) => prevItem.optionId === item.optionId),
);
return [...prevData, ...filteredData];
});
}
} catch (error) {
console.log(error);
}
};
fn();
}, 1000);
以上就是对ProFormSelect在使用过程中遇到的问题总结,如果有帮助,可以点个赞哦。