简体   繁体   中英

react-select 2 setting value/label

I am using react-select 2 and trying to set value on form that needs to perform update of some data fetched from server.

I have tried solution:

handleSelectChange(selectedOption){
 this.setState({ selectedOption });
}

const options = [
  { value: 'Value 1', label: 'Value 1' },
  { value: 'Value 2', label: 'Value 2' },

]

<Select
   options={options}
   onChange={(selectedOption)=>this.handleSelectChange(selectedOption)}
   autoFocus={true}
   value={options.find(option => option.value === data.valueTyppe)}

/>

By using this it is not possible to change (visualy) label in select input - value changes on select but label stays as one defined by data.ValueType.

I think your problem comes from not allowing full control of the Select input.The value of the Select input should be the component state value property, same as the onChange calback is.

return(
      <Select
      options={options}
      onChange={this.handleSelectChange}
      autoFocus={true}
      value={this.state.selectedOption}
   />

try this working examle

I have used this solution and it works for me. First Value/Label pair is set as on defined in options that have value === data.FacilityType (saved string in database).

Then it enables change of option where value/label pair is also updated in Select.

<Select
  options={options}
  onChange={(selectedOption)=>this.handleSelectChange(selectedOption)}
  autoFocus={true}
  defaultValue={options.find(option => option.value === data.facilityType)}

/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM