简体   繁体   English

react-select 2 设置值/标签

[英]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.我正在使用 react-select 2 并尝试在需要执行更新从服务器获取的某些数据的表单上设置值。

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.通过使用它,不可能在选择输入中更改(视觉上)标签 - 选择时的值更改但标签保持为由 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.我认为您的问题来自不允许完全控制 Select 输入。 Select 输入的值应该是组件状态值属性,与 onChange 回调相同。

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).第一个值/标签对设置为在具有值 === data.FacilityType(数据库中保存的字符串)的选项中定义。

Then it enables change of option where value/label pair is also updated in Select.然后它启用选项的更改,其中值/标签对也在 Select 中更新。

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

/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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