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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| import React, { useState, useEffect, useMemo, useCallback } from 'react'; import { Select, Spin } from 'antd';
interface OptionsConfigType { optionValue: string; optionName: string; }
interface IProps { url: string; OptionsConfig: OptionsConfigType; handleSelect: (value, options?) => void; }
const { Option } = Select; export const SuperSelect: React.FC<IProps> = (props) => { const { url, OptionsConfig, handleSelect } = props; const [pagination, setPagination] = useState<any>({ current: 1, size: 10 }); // 默认分页 const [isLoading, setIsLoading] = useState(false); // loading动画控制 const [total, setTotal] = useState<number>(0); // 记录总数,来判断是否继续请求 const [list, setList] = useState<any[]>([]);
const handleGetData = useCallback(() => { if (list.length && list.length >= total) return; // 判断是否继续请求 setIsLoading(true); fetch(url) // 模拟请求 .then(res => res.json()) .then((json) => { setList([...list, ...json.records]); setTotal(json.total); setIsLoading(false); }) }, [list, total])
useEffect(() => { handleGetData(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [])
const onSelect = useCallback((value, options) => { handleSelect && handleSelect(value, options); }, [handleSelect])
const dropdownRender = useCallback((menu) => { return ( <Spin spinning={isLoading}> {menu} </Spin> ) }, [isLoading])
const onPopupScroll = useCallback(async(e) => { const { target } = e; if (target.scrollTop + target.offsetHeight === target.scrollHeight) { const { current } = pagination; setPagination({ current: current + 1, size: 10 }); handleGetData(); } }, [handleGetData, pagination])
return useMemo(() => { return ( <> <Select style={{ width: 220 }} onPopupScroll={onPopupScroll} onSelect={onSelect} dropdownRender={(menu) => dropdownRender(menu)} > { list?.length > 0 && list.map((item, index) => { return <Option key={item[OptionsConfig.optionValue]} value={item[OptionsConfig.optionValue]}>{item[OptionsConfig.optionName]}-{index}</Option> }) } </Select> </> ) }, [OptionsConfig.optionName, OptionsConfig.optionValue, dropdownRender, list, onPopupScroll, onSelect]) }
export default SuperSelect;
|