React-Select 自定义选项数组?

Mik*_*lad 4 javascript reactjs

我正在尝试使用react-select, https://react-select.com/,并且options道具的强制格式似乎是{value:something, label:something}.

我有一个包含其他键、值对的对象列表,我的问题是是否有任何解决方法,not having to modify the array因为如果我修改它,这意味着select component将不会返回初始数组的对象,因此我将不得不再次映射它们.

options = [
    {name: 'opt1', descr:'descr1'},
    {name: 'opt2', descr:'descr2'},
    {name: 'opt3', descr:'descr3'},
]
Run Code Online (Sandbox Code Playgroud)

例如,Vue我可以选择key将用作的label

视图:

:items="options.name"
Run Code Online (Sandbox Code Playgroud)

在反应中,我将不得不执行以下操作:

this.new_options = []
this.options.forEach(element => {
    this.new_options.push({
        value : element.name,
        label : element.name,
    })
})
Run Code Online (Sandbox Code Playgroud)

在选择中:

                  <Select
                        name="selectedWires"
                        //closeMenuOnSelect={false}
                        components={makeAnimated()}
                        onChange={this.handleSelectChange('selectedWires')}
                        options={this.new_options}
                        isMulti
                    />
Run Code Online (Sandbox Code Playgroud)

Agn*_*ney 13

react-select您可以通过以下方式映射选项:

const options = [
  { val: 'chocolate', desc: 'Chocolate' },
  { val: 'strawberry', desc: 'Strawberry' },
  { val: 'vanilla', desc: 'Vanilla' }
]

<Select
  options={options}
  getOptionLabel={(option)=>option.desc}
  getOptionValue={(option)=>option.val}
/>
Run Code Online (Sandbox Code Playgroud)

文档

现场演示