Provinces.tsx
3.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* eslint-disable @typescript-eslint/no-shadow */
import React from 'react';
import type { CascaderProps } from 'antd';
import { Cascader } from 'antd'
import { requestCode } from '@/services/server';
/**
* @span 省市区三级联动选择组件
*/
export interface ProvincesCacaderPorps extends Partial<CascaderProps> {
dept?: number; // 联动层级
}
export default class ProvincesCacader extends React.Component<ProvincesCacaderPorps> {
state = {
options: [],
};
componentDidMount() {
this.getLoadData()([]);
}
render() {
const { value, onChange } = this.props;
const { options } = this.state;
const loadData = this.getLoadData();
if (options.length && value && value[0]) {
const keys: any[] = value;
const node = [];
let [data]: any = options.filter((item: any) => item.id === keys[0]);
if (value && data) {
// eslint-disable-next-line no-plusplus
for (let i = 1; i < value.length; i++) {
if (data.children) {
[data] = data.children.filter((item: any) => item.id === keys[i]);
if (!data) break;
node.push(data);
} else {
node.push(data);
loadData(node);
break;
}
}
}
}
return (
<Cascader
allowClear
fieldNames={{
label: 'name',
value: 'id',
}}
defaultValue={this.props.value}
loadData={loadData}
onChange={(values: any[], options?: any[]) => {
this.setState({ value: values });
if(onChange) onChange(values, options);
}}
placeholder="请选择位置"
{...this.props}
options={options}
></Cascader>
);
}
getLoadData() {
let loadData;
const { dept } = this.props;
const { options } = this.state;
// eslint-disable-next-line prefer-const
loadData = (node: any) => {
const option = node[node.length - 1] || {};
if (option.loading) return;
option.loading = true;
// eslint-disable-next-line default-case
switch (node.length) {
case 0:
requestCode('bdt.basic.province.search',{
pageSize: 0,
countryId: 86,
}).then((res: any) => {
this.setState({
options: res.result.map((item: any) => {
return {
...item,
isLeaf: dept === 1,
};
}),
});
});
break;
case 1:
requestCode('bdt.basic.city.search', { provinceId: option.id, pageSize: 0 }).then((res: any) => {
option.loading = false;
option.children = res.result.map((item: any) => {
return {
...item,
isLeaf: dept === 2,
};
});
this.setState({ options });
});
break;
case 2:
requestCode('bdt.basic.district.search', { cityId: option.id, pageSize: 0 }).then((res: any) => {
option.loading = false;
option.children = res.result.map((item: any) => {
return {
...item,
isLeaf: true,
};
});
this.setState({ options });
});
break;
}
}
return loadData;
}
}