React实现国家-州级联依赖下拉菜单 选中国家后动态加载对应选项
React 级联下拉(国家-州联动)实现方案
直接基于你提供的初始代码修改即可,核心是用React状态管理选中值和联动可选项,具体实现逻辑如下:
- 首先修正基础写法问题:你初始代码里的
drop是静态数据源,不能直接当函数调用,事件处理函数也没加声明关键字,先把静态数据源抽成常量,引入useState做响应式状态管理。 - 维护3个核心状态:当前选中的国家ID、当前国家对应的可选州列表、当前选中的州ID。
- 给国家下拉框绑定change事件:选中国家时拿到对应的CountryId,从全量州数据里过滤出匹配当前国家ID的条目,更新到可选州列表里,同时清空之前选中的州值,避免残留不属于当前国家的无效选项。
- 渲染两个选择框:国家下拉遍历全量国家数据渲染选项;州下拉遍历过滤后的可选州列表渲染,没选国家的时候直接禁用州下拉,放默认提示项即可。
注意:你初始代码里的州数据只放了印度(CountryId=1)的条目,其他国家的州按相同数据结构补全就行,过滤逻辑不需要调整。
完整可运行代码如下:
import { useState } from 'react'; // 静态区域数据抽到组件外,避免每次渲染重复创建 const regionData = { Country: [ { CountryName: "India", CountryId: 1 }, { CountryName: "UK", CountryId: 2 }, { CountryName: "US", CountryId: 3 }, { CountryName: "UAE", CountryId: 4 }, ], State: [ { name: "Delhi", StateId: 1, CountryId: 1 }, { name: "Punjab", StateId: 2, CountryId: 1 }, { name: "Chandigarh", StateId: 3, CountryId: 1 }, { name: "Haryana", StateId: 4, CountryId: 1 }, { name: "Goa", StateId: 5, CountryId: 1 }, { name: "Mumbai", StateId: 6, CountryId: 1 }, { name: "London", StateId: 7, CountryId: 2 }, { name: "Manchester", StateId: 8, CountryId: 2 }, { name: "New York", StateId: 9, CountryId: 3 }, { name: "California", StateId: 10, CountryId: 3 }, { name: "Dubai", StateId: 11, CountryId: 4 }, ], } function App() { const [selectedCountryId, setSelectedCountryId] = useState(''); const [availableStates, setAvailableStates] = useState([]); const [selectedStateId, setSelectedStateId] = useState(''); // 国家选择联动逻辑 const handleCountryChange = (e) => { const countryId = Number(e.target.value); setSelectedCountryId(countryId); // 过滤匹配当前国家的州 const matchedStates = regionData.State.filter(state => state.CountryId === countryId); setAvailableStates(matchedStates); // 重置已选州,避免无效值残留 setSelectedStateId(''); } const handleStateChange = (e) => { setSelectedStateId(Number(e.target.value)); } return ( <div style={{ padding: '20px', display: 'flex', gap: '20px' }}> <div> <label>国家:</label> <select value={selectedCountryId} onChange={handleCountryChange}> <option value="" disabled>请选择国家</option> {regionData.Country.map(country => ( <option key={country.CountryId} value={country.CountryId}> {country.CountryName} </option> ))} </select> </div> <div> <label>州/省:</label> <select value={selectedStateId} onChange={handleStateChange} disabled={!selectedCountryId} > <option value="" disabled>请选择州</option> {availableStates.map(state => ( <option key={state.StateId} value={state.StateId}> {state.name} </option> ))} </select> </div> </div> ) } export default App;
几个容易踩的细节问题:
- 下拉选项的value和数据源里的ID类型要统一,都用数字的话记得把
e.target.value转成Number,不然字符串和数字做全等匹配会过滤失败。 - 遍历生成的option一定要加唯一
key属性,不然React会抛渲染警告。 - 切换国家的时候必须重置已选中的州值,不然会出现选了印度的德里,切到美国之后下拉框还显示德里的bug。
内容的提问来源于stack exchange,提问作者gourav kumar
相关产品推荐
相关产品推荐

