REACT - 将选择从下拉列表变成标签

REACT - Turn a selection from a dropdown to a tag label

有没有办法将选择从下拉列表转换为具有适当颜色的标签(见图)。

ItemDisplay.jsx

export default function ItemDisplay() {
...
  const colourStyles = {
    singleValue: (provided, { data }) => ({
      ...provided,
      backgroundColor:
        data.value === "Good"
          ? "#36B37E"
          : data.value === "Medium"
          ? "#FF8B00"
          : data.value === "Bad"
          ? "#FF5630"
          : ""
    })
  };
...
  return (
      ...
          <Dropdown
            style={styles.select}
            options={TASTE}
            defaultValue={TASTE.find((t) => t.label === item.taste)}
            styleSelect={colourStyles}
          />
        </div> 
       ...      
  );
}

您可以做的是在每次 select 元素时使用另一个 Tag 组件替换下拉列表:

export default function CustomDropdown({
  style,
  options,
  styleSelect,
  defaultValue
}) {
  const [selected, setSelected] = React.useState(defaultValue);
  const backgroundColor = styleSelect?.(selected?.label) ?? "grey";
  
  const Tag = () => {
    return (
      <div style={{display: "flex", justifyContent:"space-around", padding: "0.2em",backgroundColor: backgroundColor, borderRadius: "2px", color:"white"}}>
        {selected.label}
        <button
        style={{backgroundColor: "transparent", color:"white", border: "none", cursor: "pointer"}} 
        onClick={() => setSelected(null)}>x</button>
      </div>
    )
  }
  return (
    <div style={style}>
      {selected ?
       <Tag />
       :
      <Select
        value={selected}
        onChange={setSelected}
        options={options}
      />
      }
      
    </div>
  );
}

理想情况下,您应该为 Tag 组件创建一个合适的文件,并将 selected 属性传递给该组件。

我还更改了 colourStyles 的实现,并使其成为 returns 基于 selection 的正确颜色的函数:

const colourStyles = (selected) => {
     switch(selected){
       case "Good": 
        return "#36B37E";
       case "Medium": 
        return "#FF8B00";
       case "Bad": 
        return "#FF5630";
       default:
         return ""
     }
  };