首页 > 解决方案 > 如何将选项中的额外键传递给 react-dropdown 并从 onChange 道具中取回它们?

问题描述

我正在使用这个下拉库react-dropdown

export const currencies = [
    { value: 'USD', label: '$ USD', currencySign: "$" },
    { value: 'INR', label: '₹ INR', currencySign: "₹" },
    { value: 'CAD', label: 'C$ CAD', currencySign: "C$"  }
]


<Dropdown 
    options={currencies}
    onChange={newSelectedOption => console.log(newSelectedOption)} // Getting an object with only 2 keys: "label" & "value". The third key "currencySign" is not there!
/>

有什么方法可以在 onChange 对象中获取“currencySign”?

谢谢!

2020 年 10 月 13 日更新:似乎 react-dropdown 库不提供此功能。

标签: javascriptreactjstypescriptreact-select

解决方案


如果您可以访问处理程序中的选项数组,则可以编写一个辅助函数

Dropdown 
    options={currencies}
    onChange={onChange}
/>

onChange(selected){
  var itemWithCurrency = this.findSelected(selected.value,  this.currencies)
}

findSelected(value, items){
  return items.find(item => item.value === value)
}

推荐阅读