我是 React js 的新手。我正在写一个类,其中有两个 html“选择”。第一个设置城市,第二个设置城市。当我单击按钮时,我应该获取用户选择的信息。我保持/更新城市状态,但我不知道如何在城市发生变化时设置酒店状态。我需要另一个单独的组件吗?
class CalendarForm extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedCity: "Warsaw",
selectedHotel: "Hilton"
};
}
showResult() {
const data = {
dzień: this.props.selectedDay,
miasto: this.state.selectedCity,
hotel: this.state.selectedHotel
};
console.log(data);
}
render() {
const { selectedCity } = this.state;
const CalendarForm = this.props.calendarForm;
const selectedDay = this.props.selectedDay;
const getHotels = () => {
const filterSelectedCity = CalendarForm.filter(
({ city }) => city === selectedCity
)[0];
return (
<div>
<select
onChange={e => this.setState({ selectedHotel: e.target.value })}
>
{filterSelectedCity.hotels.map((hotel, index) => (
<option key={index} value={hotel}>
{hotel}
</option>
))}
</select>
</div>
);
};
return (
<div>
<select onChange={e => this.setState({ selectedCity: e.target.value })}>
{CalendarForm.map(({ city, index }) => (
<option key={index} value={city}>
{city}
</option>
))}
</select>
{getHotels()}
<button onClick={this.showResult.bind(this)} type="button">
click
</button>
</div>
);
}
}
export default CalendarForm;
最佳答案
您的代码已经有了一些细微的变化:here's a stackblitz这表明城市更改后酒店选择正在更新。
需要注意的几点:
- 我将城市选择的
onChange
处理程序重构为updateCity
updateCity
还将state.selectedHotel
更新为城市的第一家酒店- 你应该将酒店和城市
select
的value
属性分别绑定(bind)到selectedCity
和selectedHotel
以选择相应的选项
updateCity
代码:
updateCity(event) {
const selectedCity = event.target.value;
const selectedHotel = this.props.calendarForm.find(({ city }) => city === selectedCity)
.hotels[0];
this.setState((oldState) => ({...oldState, selectedCity, selectedHotel }));
}
关于javascript - 呈现选择时的ReactJS setState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51583703/