城市选择react
import React, { useEffect, useState } from 'react'; import { Cascader } from 'antd'; import { SysCityList } from '../../services/citys'; interface Option { value?: string | number | null; label: React.ReactNode; children?: Option[]; isLeaf?: boolean; loading?: boolean; } const App: React.FC = () => { const [options, setOptions] = useState<Option[]>([]); useEffect(() => { fetchApi([0]); }, []); const fetchApi = (val: any) => { const type = val?.length; // 1 - 省, 2 - 市, 3 - 区 const id = val ? val[val.length - 1] : ''; SysCityList({ cityId: id }).then((res: any) => { const data = res.data.map((i: any) => { const obj = { value: i.id, label: i.name, isLeaf: false }; return obj; }); if (val[0] === 0) { // 初次调用 setOptions(data); } else { if (type === 1) { setOptions((data: any) => data.map((item: any) => { if (item.value === id) { return { ...item, children: res.data.map((i: any) => { const obj = { value: i.id, label: i.name, isLeaf: res.data.length > 0 ? false : true }; return obj; }) }; } else { return item; } }) ); } else if (type === 2) { setOptions((data) => data.map((item: any) => { if (item.value === val[0]) { return { ...item, children: item.children.map((son: any) => { if (son.value === val[1]) { return { ...son, children: res.data.map((i: any) => { const obj = { value: i.id, label: i.name }; return obj; }) }; } else { return son; } }) }; } else { return item; } }) ); } } }); }; const onChange = async (value: (string | number)[], selectedOptions: Option[]) => { console.log(value, selectedOptions); fetchApi(value); }; return <Cascader options={options} onChange={onChange} changeOnSelect />; }; export default App;
本文来自博客园,作者:zjxgdq,转载请注明原文链接:https://www.cnblogs.com/zjxzhj/p/17302228.html