简体   繁体   中英

React: Can't select dropdown menu options after assigning value attribute to component's state

I have a React component that renders a dropdown menu.The component's state is updated when it receives props from its parent. I've set the 'value' attribute of the <'select> element to the state so that it re-renders when new props are received. This successfully re-renders the value in the dropdown menu when props are received but disables it from selecting a different option.

<select
      type="text"
      name="dogOwnerType"
      id="dogOwnerType"
      className="form-control"
      data-bv-field="dogOwnerType"
      value={this.state.dogOwnerType.ownerType}
    >
      <option value="">Choose Owner Type</option>
      <option value="DogLover">DogLover</option>
      <option value="DogOwner">DogOwner</option>
    </select>

To be able to change the value; you should add an onChange handler, which sets the new value to the state.

    // define function which sets new value to state
    updateOwnerType = event => {
        this.setState({
            dogOwnerType: { 
                ...this.state.dogOwnerType, 
                ownerType: event.target.value,
           })
    }

    {/* add your onChange handler to select element */}
    <select
          type="text"
          name="dogOwnerType"
          id="dogOwnerType"
          className="form-control"
          data-bv-field="dogOwnerType"
          onChange={this.updateOwnerType}
          value={this.state.dogOwnerType.ownerType}
        >

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM