【发布时间】:2021-03-10 09:52:42
【问题描述】:
我想创建 3 个下拉菜单,例如国家、州、城市。根据国家选项中的选择,它应该填充州,并且根据国家和州选择的选项,城市下拉应该在 react js 中填充自己。提前致谢
我想在美国国家/地区添加更多州
componentDidMount() {
this.setState({
countries: [
{
name: "Germany",
states: [
{
name: "A",
cities: ["Duesseldorf", "Leinfelden-Echterdingen", "Eschborn"]
}
]
},
{ name: "Spain", states: [{ name: "B", cities: ["Barcelona"] }] },
{ name: "USA", states: [{ name: "C", cities: ["Downers Grove"] }] },
{
name: "Mexico",
states: [{ name: ["D", "F", "H"], cities: ["Puebla"] }]
},
{
name: "India",
states: [
{ name: "E", cities: ["Delhi", "Kolkata", "Mumbai", "Bangalore"] }
]
}
]
});
}
changeCountry(event) {
this.setState({ selectedCountry: event.target.value });
this.setState({
states: this.state.countries.find(
(cntry) => cntry.name === event.target.value
).states
});
}
changeState(event) {
this.setState({ selectedState: event.target.value });
const stats = this.state.countries.find(
(cntry) => cntry.name === this.state.selectedCountry
).states;
this.setState({
cities: stats.find((stat) => stat.name === event.target.value).cities
});
}
我想在一个国家/地区显示更多州和城市(3 个下拉菜单)
render() {
return (
<div id="container">
<h2>Cascading or Dependent Dropdown using React</h2>
<div>
<label>Country</label>
<select
placeholder="Country"
value={this.state.selectedCountry}
onChange={this.changeCountry}
>
<option>--Choose Country--</option>
{this.state.countries.map((e, key) => {
return <option key={key}>{e.name}</option>;
})}
</select>
</div>
<div>
<label>State</label>
<select
placeholder="State"
value={this.state.selectedState}
onChange={this.changeState}
>
<option>--Choose State--</option>
{this.state.states.map((e, key) => {
return <option key={key}>{e.name}</option>;
})}
</select>
</div>
<div>
<label>City</label>
<select placeholder="City">
<option>--Choose City--</option>
{this.state.cities.map((e, key) => {
return <option key={key}>{e}</option>;
})}
</select>
</div>
</div>
);
}
}
【问题讨论】:
标签: reactjs