【问题标题】:How to create dropdown list with description in React如何在 React 中创建带有描述的下拉列表
【发布时间】:2021-04-30 07:56:11
【问题描述】:

我正在尝试在 React 中创建一个带有描述的下拉列表。参考下图:

还有其他方法可以使用引导程序或 Material-UI 来实现吗? 我正在使用react-select npm 包作为下拉列表。您可以在下面找到实时链接和代码:

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}
  />
);

【问题讨论】:

  • 您的图片链接设置不正确,请重新检查

标签: reactjs bootstrap-4 drop-down-menu dropdown react-select


【解决方案1】:

您可以覆盖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 }}
  />
);

现场演示

【讨论】:

    猜你喜欢
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    相关资源
    最近更新 更多