如何在 React 中创建带有描述的下拉列表

How to create dropdown list with description in React

我正在尝试在 React 中创建一个带有描述的下拉列表。作为参考,您可以查看下图:

有没有其他方法可以使用 bootstrap 或 Material-UI 来实现这个目标? 我正在为下拉列表使用 react-select npm 包。你可以找到实时 link 和下面的代码:

https://codesandbox.io/embed/react-select-selected-option-background-color-forked-jpu99?fontsize=14&hidenavigation=1&theme=dark

const colourOptions = [
  { value: "red", label: "Red" ,description:"Test description for red"},
  { value: "green", label: "Green", description:"Test description for green" },
  { value: "blue", label: "Blue", description:"Test description for blue" }
];

//for styling

const colourStyles = {
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    // const color = chroma(data.color);
    console.log({ data, isDisabled, isFocused, isSelected });
    return {
      ...styles,
      backgroundColor: isFocused ? "#00A3BE" : "#191D2F",
      font: "Segoe UI",
      color: "#F9FAFC"
    };
  }
};

export default () => (
  <Select
    defaultValue={colourOptions[1]}
    label="Single select"
    options={colourOptions}
    styles={colourStyles}
  />
);

您可以覆盖 Option component 并提供您自己的 Option 可以同时显示标题和描述:

import Select, { components } from "react-select";

const colourStyles = {
  option: (styles, { data, isDisabled, isFocused, isSelected }) => {
    return {
      ...styles,
      backgroundColor: isFocused ? "#00A3BE" : "",

      color: isFocused ? "#F9FAFC" : "#191D2F",
      display: "flex",
      paddingLeft: 0,

      "& .left": {
        display: "flex",
        justifyContent: "center",
        width: 60,
        marginTop: 3
      },
      "& .right": {
        width: "100%"
      },

      "& .right > .title": {
        display: "block",
        margin: "5px 0"
      }
    };
  }
};

const Option = (props) => {
  return (
    <components.Option {...props}>
      <div className="left">{props.isSelected ? "✔" : ""}</div>
      <div className="right">
        <strong className="title">{props.data.label}</strong>
        <div>{props.data.description}</div>
      </div>
    </components.Option>
  );
};

export default () => (
  <Select
    defaultValue={colourOptions[1]}
    label="Single select"
    options={colourOptions}
    styles={colourStyles}
    components={{ Option }}
  />
);

现场演示