封装组件:由于需求特殊,可以将获取数据的方法放到外面
import React, { useState, useEffect } from 'react';
import { Select } from 'antd';
const { Option } = Select;
const LargeSelect = ({options,selectChange,setting,defaultValue,onChange}) => {
const [data, setData] = useState([]); // 保存全部数据
const [loading, setLoading] = useState(false);
const [offset, setOffset] = useState(0);
const fetchData = () => {
setLoading(true)
selectChange({'limit':50,'offset':offset}).then((res)=>{
setData(prevData => [...prevData, ...res]);
setOffset(prev => prev + 50);
setLoading(false)
})
};
useEffect(() => {
fetchData();
}, []);
useEffect(()=>{
onChange(defaultValue)
},[defaultValue])
const handleSearch=(value)=>{
setLoading(true)
setOffset(0);
setData([]);
selectChange({'q':value}).then((res)=>{
setData(prevData => [...prevData, ...res]);
setLoading(false)
})
}
const handleScroll = e => {
const target = e.target;
// 判断是否滚动到底部
if (target.scrollTop + target.offsetHeight+2 >target.scrollHeight && !loading) {
// 判断上次获取的数据条数是否等于50 等于的话就再获取,否则无需根据高度反复获取
if(data.length == offset){
fetchData();
}
}
};
return (
<Select
disabled={ setting?.disabled }
placeholder={ setting?.placeholder }
style={{ width: '100%' }}
onPopupScroll={handleScroll}
notFoundContent={loading ? <span>Loading...</span> : null}
showSearch
defaultActiveFirstOption={false}
filterOption={false}
loading={loading}
allowClear
onSearch={handleSearch}
defaultValue={defaultValue}
onChange={onChange}
>
{data?.map((option, optionIndex) => (
<Option
key={optionIndex}
value={
option[options?.optionsDict?.value] || option.value
}
>
{option[options?.optionsDict?.label] || option.label}
</Option>
))}
</Select>
);
};
export default LargeSelect;
使用组件
const [selectValue, setSelectValue] = useState("");
// 设备lazySelect
const selectChange = (params) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
// axios 请求和处理
}, 100);
});
};
const getDevice = (defaultValue, setting) => {
return (
<LazySelect
defaultValue={defaultValue || null}
setting={{
placeholder: setting.placeholder || "",
disabled: setting.disabled || false,
}}
options={{
optionsDict: {
label: "display",
value: "id",
},
}}
onChange={(value) => {
setSelectValue(value);
}}
selectChange={selectChange}
/>
);
};