1

我想根据提供的选项修改对象singleValue中的“选定”颜色。styles

  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..
    })
  }; 
4

1 回答 1

1

使用样式映射对象:

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}
    />
  );
}
于 2020-10-21T21:16:38.610 回答