簡體   English   中英

反應:將值屬性分配給組件的狀態后,無法選擇下拉菜單選項

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

我有一個可渲染下拉菜單的React組件,當組件從其父對象接收道具時會更新其狀態。 我已經將<'select>元素的'value'屬性設置為狀態,以便在收到新道具時重新渲染。 當收到道具時,這將成功地在下拉菜單中重新渲染該值,但使它無法選擇其他選項。

<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>

能夠更改值; 您應該添加一個onChange處理函數,該處理函數會將新值設置為狀態。

    // 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}
        >

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM