javascript - 如何在第二个自动完成输入中获取特定数据,这取决于在 React.js 中的第一个输入中键入的内容?
问题描述
好的,所以我不知道如何正确表达我的简单问题,因为它很简单,我猜。
基本上,我在我的 React 项目中完成了一个自动完成功能。我有两个输入“国家”和“城市”。当我输入一个国家/地区时,我的自动完成功能很好,可以给我建议,但现在我必须为我的第二个输入做同样的事情,所以它会给我一个城市列表,这取决于在“国家”输入中输入的国家...
“英国”=>“伦敦、伯明翰、拜顿等”
我怎样才能做到这一点?谢谢!
PS我已经有了所有国家和城市的列表,我只是不知道如何使第二个输入依赖于第一个中的信息。
代码在这里
Autocomplete.jsx https://github.com/lembas-cracker/Weather-app/blob/master/src/Autocomplete.jsx
Form.jsx https://github.com/lembas-cracker/Weather-app/blob/master/src/Form.jsx
解决方案
做了一个简单的例子。你的意思是这样的吗?由于您没有提供源代码的任何部分,因此我使用纯 HTMLselect
进行演示。
https://jsfiddle.net/arfeo/n5u2wwjg/204186/
class App extends React.Component {
constructor() {
super();
this.state = {
countryId: 1,
};
}
onCountryChange(countryId) {
this.setState({ countryId: parseInt(countryId) });
}
render() {
return (
<div>
<Input
key="countriesInput"
type="countries"
countryId={this.state.countryId}
onChange={(countryId) => this.onCountryChange(countryId)}
/>
<Input
key="citiesInput"
type="cities"
countryId={this.state.countryId}
/>
</div>
);
}
}
class Input extends React.Component {
constructor() {
super();
this.selectRef = null;
}
renderOptions() {
const countries = [
{
id: 1,
name: 'England',
},
{
id: 2,
name: 'Germany',
},
{
id: 3,
name: 'France',
},
];
const cities = [
{
countryId: 1,
cities: [
{
id: 1,
name: 'London',
},
{
id: 2,
name: 'Liverpool',
},
{
id: 3,
name: 'Salisbury'
}
],
},
{
countryId: 2,
cities: [
{
id: 4,
name: 'Berlin',
},
{
id: 5,
name: 'Frankfurt',
},
],
},
{
countryId: 3,
cities: [
{
id: 6,
name: 'Paris',
},
],
},
];
switch (this.props.type) {
case 'countries': {
return countries.map((country) => (
<option
key={country.id.toString()}
value={country.id}
>
{country.name}
</option>
));
}
case 'cities': {
const citiesMap = cities.filter((city) => city.countryId === this.props.countryId);
if (citiesMap && citiesMap[0]) {
const citiesList = citiesMap[0].cities;
if (citiesList) {
return citiesList.map((city) => (
<option
key={city.id.toString()}
value={city.id}
>
{city.name}
</option>
));
}
}
return null;
}
default: return null;
}
}
render() {
return (
<select name={this.props.type} ref={(ref) => this.selectRef = ref} onChange={() => this.props.onChange(this.selectRef.value)}>
{this.renderOptions()}
</select>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
更新
使您的
Form
组件有状态。countries
为in添加一个 state 属性Form
(让它成为countryId
)。将此属性作为道具传递给第二个
Autocomplete
组件。当第一个更改时,
Autocomplete
更改countryId
.Form
推荐阅读
- javascript - 使用 YouTube API 自动播放 Play Promise
- javascript - SyntaxError:createScript (vm.js:80:10) 处的令牌无效或意外
- node.js - 无法在 VS Code 中设置断点调试节点 Typescript
- visual-studio - winapi 奇怪字符 const char*
- android - Android Studio gradle 同步失败:没有缓存版本
- c# - C# - 无法从数据库中检索实体
- javascript - 在鼠标悬停时删除另一个 DOM 对象中第 n 个元素的类
- python - 如何列出和更改 Python heapq 中的元素而不弹出它们?
- c# - 在 C#/ASP.Net 中将数据表转换为文本而不是 JSON
- asp.net - 如何使用下拉列表从外键原始表中引用不同的列并将其保存在外键新表中?