我是React JS的新手。我正在写一个有两个html'selects'的类。第一个城市和第二个城市。当我单击按钮时,我应该获得用户选择的信息。我保留/更新了City的状态,但是我不知道在City更改后如何设置酒店的状态。我是否需要另一个单独的组件?

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更新为该城市的第一家酒店
您应将酒店和城市valueselect属性分别绑定到selectedCityselectedHotel以选择相应的option


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 }));
}

08-04 21:55