【发布时间】:2019-12-08 20:27:42
【问题描述】:
我有一个包含 2 个选择器字段的输入表单 - 国家和城市。并且城市列表必须只上传当前国家的城市。选择国家后,我在该州拥有它。但是我在过滤城市列表时遇到了问题。当我写像 filter(key => key["country"] === 1 ) 时,其中 1 是国家的 ID,它可以工作。如果比较键["country"] === this.state.country 不起作用,我该如何使用该国的当前状态?
...
onChange = event => {
this.setState({
[event.target.name]: event.target.value
});
};
getOptionItems = (Items) => Items.map(item =>
<option key={item.id} value={item.id}>
{item.name}
</option>
)
<div className="form-group">
<label htmlFor="country">Country</label>
<select
className="custom-select"
id="country"
value={this.state.country}
name="country"
onChange={this.onChange}
>
{this.getOptionItems(countries)}
</select>
</div>
<div className="form-group">
<label htmlFor="city">City</label>
<select
className="custom-select"
id="city"
value={this.state.city}
name="city"
onChange={this.onChange}
>
{Object.values(cities).filter(key => key["country"] === **what condition to write here?**).map(city =>
<option key={city.id} value={city.id}>
{city.name}
</option>
)}
【问题讨论】:
-
向我们展示
this.state.country和cities数组 -
key["country"] === this.state.country会出现什么错误 -
它显示空白字段。没有什么可以选择的
-
this.state = { ... country: "1", city: "1", .... } } 城市在这样的文件中:"1": { country: 1, name :“基辅”},“2”:{国家:1,名称:“利沃夫”},“3”:{国家:1,名称:“敖德萨”},“4”:{国家:1,名称:“ Dnipro" }, "5": { 国家: 1, 名称: "Kharkiv" }, "6": { 国家: 2, 名称: "Berlin" }, "7": { 国家: 2, 名称: "Dortmund" },“8”:{国家:2,名称:“德雷兹登”},“9”:{国家:2,名称:“汉堡”},“10”:{国家:2,名称:“科隆”}, .....
标签: javascript reactjs input selector