如何在选项中使用相同的对象进行更改
<Select
options={this.state.materialunit.map(obj => {return({value: obj.materialunitID, label: obj.unitName + ': ' + obj.materialName})})}
onChange={e => this.setState({unitPrice: obj.unitPrice })}
/>
为了构造反应选择的选项,我建议将逻辑移动到一个方法。所以,代码看起来像
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中设置valueKey
和labelKey
,在v2中可以分别使用getOptionLabel
和getOptionValue
方法。希望这会有所帮助。 Documentation here