react-select 根据选项更改单值颜色

react-select change singleValue color based on options

我想根据提供的选项修改 styles 对象中的 'selected' singleValue 颜色。

  const statusOptions = [
    { value: "NEW", label: i18n._(t`NEW`) },
    { value: "DNC", label: i18n._(t`DNC`) },
    { value: "WON", label: i18n._(t`WON`) },
    { value: "LOST", label: i18n._(t`LOST`) },
  ];

比如选择“NEW”的选项,我希望字体颜色为红色,如果是“WON”,则为绿色,以此类推。我在将 if 语句放入样式对象时遇到问题。我看到放入三元语句很简单,但是如何添加更多“复杂”逻辑?

  const customStyles = {
    ...
    singleValue: (provided) => ({  
      ...provided,
      color: 'red' <----- something like if('NEW') { color: 'green' } etc..
    })
  }; 

使用样式映射对象:

import React from 'react';
import Select from 'react-select';

const statusOptions = [
  { value: 'NEW', label: 'NEW' },
  { value: 'DNC', label: 'DNC' },
  { value: 'WON', label: 'WON' },
  { value: 'LOST', label: 'LOST' },
];

const styleMap = {
  NEW: 'red',
  DNC: 'blue',
};

const colourStyles = {
  singleValue: (provided, { data }) => ({
    ...provided,
    color: styleMap[data.value] ? styleMap[data.value] : 'defaultColor',
    // specify a fallback color here for those values not accounted for in the styleMap
  }),
};

export default function SelectColorThing() {
  return (
    <Select
      options={statusOptions}
      styles={colourStyles}
    />
  );
}