React函数组件中为country-state-city组件设置预定义值及数据回显
React函数组件:基于country-state-city的三级联动选择器(支持预定义值)
需求说明
在React函数组件中,借助country-state-city npm包实现国家、州、城市的三级联动Form.Select组件,同时支持为三级选择器设置预定义的初始值。
核心代码实现
变量与数据初始化
import { Country, State, City } from 'country-state-city'; import { useRef, useEffect, useState } from 'react'; import { Form } from 'antd'; // 假设使用Ant Design的Form组件 const [countrydata, setCountrydata] = useState([]); const [statedata, setStatedata] = useState([]); const [citydata, setCitydata] = useState([]); const [country, setCountry] = useState(''); const [states, setStates] = useState(''); const [Countryname, setCountryname] = useState(''); const [Statename, setStatename] = useState(''); const selectRef = useRef(""); const selectRefst = useRef(""); const selectRefct = useRef(""); // 初始化加载所有国家数据 useEffect(() => { setCountrydata(Country.getAllCountries()); }, []); // 监听国家/州变化,联动更新州/城市数据 useEffect(() => { if (country) { setStatedata(State.getStatesOfCountry(country)); // 若有预设州值,同步加载对应城市 if (states) { setCitydata(City.getCitiesOfState(country, states)); } } else { setStatedata([]); setCitydata([]); } }, [country, states]);
选择器事件处理
// 国家选择事件 const fndcntryname = (val) => { setStates(""); // 切换国家时重置州选择 setCountry(val); if (val) { const cntryname = Country.getCountryByCode(val); setCountryname(cntryname.name); } }; // 州选择事件 const fndstatname = (statval, countryVal) => { setStates(statval); if (statval && countryVal) { const statname = State.getStateByCodeAndCountry(statval, countryVal); setStatename(statname.name); } };
预定义初始值设置方法
如果需要设置默认的国家、州、城市,只需在组件初始化时为对应状态赋值,触发联动逻辑:
useEffect(() => { // 示例:预设美国(US)、加利福尼亚州(CA) const defaultCountry = "US"; const defaultState = "CA"; setCountry(defaultCountry); setStates(defaultState); // 直接获取预设值的名称 const defaultCountryName = Country.getCountryByCode(defaultCountry).name; const defaultStateName = State.getStateByCodeAndCountry(defaultState, defaultCountry).name; setCountryname(defaultCountryName); setStatename(defaultStateName); }, []);
组件渲染示例(以Ant Design为例)
<Form layout="vertical"> <Form.Item label="国家"> <Form.Select ref={selectRef} value={country} onChange={fndcntryname} placeholder="选择国家" > {countrydata.map(item => ( <option key={item.isoCode} value={item.isoCode}> {item.name} </option> ))} </Form.Select> </Form.Item> <Form.Item label="州/省"> <Form.Select ref={selectRefst} value={states} onChange={(val) => fndstatname(val, country)} placeholder="选择州/省" disabled={!country} > {statedata.map(item => ( <option key={item.isoCode} value={item.isoCode}> {item.name} </option> ))} </Form.Select> </Form.Item> <Form.Item label="城市"> <Form.Select ref={selectRefct} placeholder="选择城市" disabled={!states} > {citydata.map(item => ( <option key={item.name} value={item.name}> {item.name} </option> ))} </Form.Select> </Form.Item> </Form>
内容的提问来源于stack exchange,提问作者Akila Shalini
相关产品推荐
相关产品推荐

