如何在 react-select 中映射状态变量?

How to map state variable in react-select?

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

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

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

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