第2世界
发布于 2023-04-21 / 5 阅读 / 0 评论 / 0 点赞

antd级联选择动态加载实现的省市区地址选择组件

项目中用到这个省市区地址选择的功能,参考了https://www.jianshu.com/p/5db5fe9da5b6 ,修复了其中存在的一些问题。

import type {FC} from 'react';
import {Cascader} from "antd";
// @ts-ignore
import provinces from "china-division/dist/provinces";
// @ts-ignore
import cities from "china-division/dist/cities";
// @ts-ignore
import areas from "china-division/dist/areas";
​
type AntdInputProps = {
  placeholder?: string;
  onChangeProps?: (v: any) => void;
  allowClear?: boolean;
};
​
areas.forEach((area: { cityCode: string; name: string; code: any; }, id: number) => {
  const matchCity = cities.filter((city: { code: string; }) => city.code === area.cityCode)[0];
  if (matchCity) {
    matchCity.children = matchCity.children || [];
    matchCity.children.push({
      label: area.name,
      value: area.code,
      id
   });
 }
});
​
cities.forEach((city: { provinceCode: any; name: string; string: any; children: any; code?: string }, id: number) => {
  const matchProvince = provinces.filter(
   (province: { code: string; }) => province.code === city.provinceCode
 )[0];
  if (matchProvince) {
    matchProvince.children = matchProvince.children || [];
    matchProvince.children.push({
      label: city.name,
      value: city.code,
      id,
      children: city.children
   });
 }
});
​
const options = provinces.map((province: { name: any; code: any; children: any; }, id: number) => ({
  label: province.name,
  value: province.code,
  id,
  children: province.children
}));
​
//console.log('options',options);
​
const AntdCascader: FC<any> = (props) => {
  const {
    placeholder = '请选择省市区',
    onChangeProps,
    allowClear = true,
 } = props;
​
// console.log(cities);
​
  return (
    <div>
      <Cascader
       {...props}
        options={options}
        showSearch
        placeholder={placeholder}
        onChange={onChangeProps}
        allowClear={allowClear}
      />
    </div>
 );
};
​
export default AntdCascader;


评论