【问题标题】:React: Can't select dropdown menu options after assigning value attribute to component's state反应:将值属性分配给组件状态后无法选择下拉菜单选项
【发布时间】:2018-03-17 23:31:59
【问题描述】:

我有一个呈现下拉菜单的 React 组件。组件的状态会在它从其父级接收到道具时更新。我已将 元素的 '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>

【问题讨论】:

  • 如果这是一个子组件,你为什么要说 this.state?
  • 我的术语可能不正确,但我称它为子组件,因为它被导入到单独的表单组件中并由单独的表单组件呈现。

标签: javascript html reactjs


【解决方案1】:

能够改变值;您应该添加一个 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}
        >

【讨论】:

    猜你喜欢
    • 2021-10-16
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-03-28
    • 2023-01-09
    • 2019-02-17
    • 2016-03-08
    • 2021-06-28
    相关资源
    最近更新 更多