【问题标题】:How to map state variable in react-select?如何在反应选择中映射状态变量?
【发布时间】:2019-05-01 11:20:52
【问题描述】:

如何在选项中使用相同的对象进行 onChange

<Select
      options={this.state.materialunit.map(obj => {return({value: obj.materialunitID, label: obj.unitName + ': ' + obj.materialName})})}
      onChange={e => this.setState({unitPrice: obj.unitPrice })}
/>

【问题讨论】:

  • 您想为this.state.materialunit 中的每个对象创建一个SelectBox 吗?或者一个带有this.state.materialunit 中数据作为选项的SelectBox ??
  • 单个选择框,以材料单元中的数据作为选项:/ 我认为我的代码不好,所以如何使用同一个对象进行 onChange?
  • 能否提供您正在使用的 react-select 版本?

标签: javascript reactjs jsx react-select


【解决方案1】:

要为反应选择构造选项,我建议将逻辑移至方法。所以,代码看起来像

onSelectMaterialUnit(selectedMaterialunit){
  //store selected option in state
  this.setState({selectedMaterialunit})

}
materialUnitOptions(){
  return this.state.materialunit.map(materialUnit => (
    {
      value: materialUnit.materialunitID,
      label: `${materialUnit.unitName}:${materialUnit.materialName}`
    }
   )
}


render(){
  return(

    <Select
       value={this.state.selectedMaterialunit}
       onChange={this.onSelectMaterialUnit}
       options={this.materialUnitOptions()}
     />

 )
}

另外,如果你想直接传递选项而不映射标签和值,你可以在 react-select v1 和 v2 中设置 valueKeylabelKey,你可以分别使用 getOptionLabelgetOptionValue 方法。希望这会有所帮助。 Documentation here

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 2020-08-10
    • 2021-05-21
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多