---
title: "使用 Ant Design ProComponents 开发表单省市区选择器"
date: 2023-01-08T18:27:50.000Z
author: Z.SHINCHVEN
tags: [Ant Design, ProComponents]
canonical: https://atlassc.net/2023/01/09/procomponents-area-select
---
使用[ProComponents](https://procomponents.ant.design/)中的[ProFormCascader](https://procomponents.ant.design/components/field-set#proformcascader)组件开发省、市、区级联选择器非常简单。

## 准备数据

首先我们需要准备省市区的数据，建议使用[wecatch/china_regions](https://github.com/wecatch/china_regions)这个仓库中的`province.json`、`city.json`、`county.json`三个文件。我把它们直接部署到了 web app 的 public 目录中当静态 API 使用。

## 整理数据结构

在前端通过网络加载好数据以后，需要对数据结构进行整理：

```typescript
const provinces = [
    // ...
];
const cities = {
    // ...
};
const counties = {
    // ...
};

const getRegionTree = () => {
  return provinces?.map(province => {
    const children = cities?.[province.id]?.map(city => {
      const _children = counties?.[city.id]?.map(county => {
        return {label: county.name, value: county.name};
      });
      return {label: city.name, value: city.name, children: _children || []};
    });
    return {label: province.name, value: province.name, children: children || []};
  });
}
```

## 在 ProFormCascader 组件中绑定数据

```tsx
// 原有数据
const customer={
    region:"上海市-市辖区-浦东区"
}

<ProFormCascader
    width={'md'} name={'region'} label={'所在地区'}
    initialValue={customer?.region?.split('-')}
    rules={[{required: true, message: '请选择所在地区'}]}
    fieldProps={{ // 绑定已经请求到的数据
        options: getRegionTree(),
    }}
    request={ // 通过网络访问数据
        async ()=>{ 
            // 模拟访问网络请求
            return getRegionTree()
        }
    }
/>
```
