地市组件

This commit is contained in:
孙景学
2025-07-24 09:10:24 +08:00
parent 77a4bd56ae
commit 2267ab2e6e
4 changed files with 92 additions and 50 deletions

View 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;

View 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});