簡體   English   中英

React-Select自定義選項數組?

[英]React-Select custom options array?

我正在嘗試使用react-selecthttps://react-select.com/options prop的強制格式似乎是{value:something, label:something}

我有一個帶有其他鍵,值對的對象列表, 我的問題是是否有not having to modify the arraynot having to modify the array解決方法,因為如果我修改它,這意味着select component將不會返回初始數組的對象所以我將不得不再次映射它們。

options = [
    {name: 'opt1', descr:'descr1'},
    {name: 'opt2', descr:'descr2'},
    {name: 'opt3', descr:'descr3'},
]

例如,在Vue我選擇了將用作labelkey

VUE:

:items="options.name"

在做出反應時,我將不得不執行以下操作:

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

在選擇中:

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

使用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}
/>

文件

現場演示

您可以使用索引作為值,然后在handleChange函數中獲取原始數組元素。

<Select 
    name="selectedWires"
    options={this.options.map((option, idx) => ({
        value: idx,
        label: option.name
    }))} 
    onChange={(selection, action) => this.handleChange(selection, action)}/>

然后在handle函數中:

handleChange(selection, action) {
    let selectedOption = this.options[selection.value];
    ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM