avatar

ShīnChvën ✨

Effective Accelerationism

Powered by Druid

使用 Ant Design ProComponents 开发表单省市区选择器

Sun Jan 08 2023

使用ProComponents中的ProFormCascader组件开发省、市、区级联选择器非常简单。

准备数据

首先我们需要准备省市区的数据,建议使用wecatch/china_regions这个仓库中的province.jsoncity.jsoncounty.json三个文件。我把它们直接部署到了 web app 的 public 目录中当静态 API 使用。

整理数据结构

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

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 组件中绑定数据

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

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