地市组件
This commit is contained in:
58
src/components/CommonSelect/DictRegionSelect.tsx
Normal file
58
src/components/CommonSelect/DictRegionSelect.tsx
Normal file
@ -0,0 +1,58 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Cascader, Spin } from 'antd';
|
||||
import type { DefaultOptionType } from 'antd/es/cascader';
|
||||
import { getChild } from './services';
|
||||
|
||||
// 只用函数式组件的 props,不声明泛型
|
||||
const DictRegionSelect: React.FC<Partial<import('antd').CascaderProps<DefaultOptionType>>> = (props) => {
|
||||
const [options, setOptions] = useState<DefaultOptionType[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
fetchRegionOptions('0').then(data => {
|
||||
setOptions(data);
|
||||
setLoading(false);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const loadData = async (selectedOptions: DefaultOptionType[]) => {
|
||||
const targetOption = selectedOptions[selectedOptions.length - 1];
|
||||
targetOption.loading = true;
|
||||
const children = await fetchRegionOptions(targetOption.value!);
|
||||
targetOption.loading = false;
|
||||
targetOption.children = children;
|
||||
setOptions([...options]);
|
||||
};
|
||||
|
||||
const fetchRegionOptions = async (pId: string | number): Promise<DefaultOptionType[]> => {
|
||||
console.log(pId,'pId');
|
||||
|
||||
const res = await getChild({ pId });
|
||||
if (res && res.code === 200 && Array.isArray(res.data)) {
|
||||
return res.data.map((item: any) => ({
|
||||
value: item.id,
|
||||
label: item.name,
|
||||
isLeaf: item.level === '2',
|
||||
}));
|
||||
}
|
||||
return [];
|
||||
};
|
||||
|
||||
// 明确指定 loadData 类型,解决 ts 推断
|
||||
const cascaderProps = {
|
||||
changeOnSelect: true,
|
||||
options,
|
||||
loadData: loadData as (selectedOptions: DefaultOptionType[]) => void, // 关键类型断言!
|
||||
placeholder: "请选择地区",
|
||||
...props,
|
||||
};
|
||||
|
||||
return (
|
||||
<Spin spinning={loading}>
|
||||
<Cascader {...cascaderProps as any} />
|
||||
</Spin>
|
||||
);
|
||||
};
|
||||
|
||||
export default DictRegionSelect;
|
11
src/components/CommonSelect/services.ts
Normal file
11
src/components/CommonSelect/services.ts
Normal file
@ -0,0 +1,11 @@
|
||||
import request from '@/utils/request';
|
||||
|
||||
|
||||
/**
|
||||
* 地市
|
||||
*/
|
||||
interface getChildParams {
|
||||
pId: string | number;
|
||||
}
|
||||
|
||||
export const getChild = (params: getChildParams) => request.get(`/v1/dictRegion/getChild`, {params});
|
Reference in New Issue
Block a user