定义自定义选项组件时,如何为 react-select 应用默认样式?

How can I apply default styles for react-select when defining a custom Option Component?

我是 React 菜鸟,也是 React 新手-select (v2).

我认为我们的场景相当简单。我们正在从 Azure 搜索(方面)中提取数据,并希望绑定到一个稍微自定义的 react-select 控件。

我们想要:

  1. 添加 badge/pill 以在下拉列表中显示计数。
  2. 避免循环遍历返回的数据以在 react-select 选项中重复值和标签。

在这个示例的帮助下(它比官方文档 IMO 更有帮助),我们已经完成了大部分工作:React-Select - Replacing Components for custom option content。唯一缺少的是应用默认的 react-select 样式(例如:悬停)。

数据示例:

const myOptions = [
    { value: 'foo', count: 100 },
    { value: 'bar', count: 200 },

];

自定义控件示例:

const CustomOption = (props:any) => {
    const { innerProps, innerRef } = props;
    return (
        <article ref={innerRef} {...innerProps} >
            <div style={{display:"inline-block"}}>{props.data.value}</div>
            <span className="badge badge-light float-right" style={{display:"inline-block"}}>{props.data.count} </span>
        </article>
    );
};

有没有办法重用默认的 react-select 样式?我在文档中遗漏了什么吗?

你真的很笨,但让我告诉你如何保持 react-select 的原始风格和行为。

无需为您的 Option 组件声明一个新容器,您需要使用原始容器并仅像这样编辑内容:

const Option = props => {
  return (
    <components.Option {...props}>
      <div style={{ display: "inline-block" }}>{props.data.value}</div>
      <span
        className="badge badge-light float-right"
        style={{ display: "inline-block" }}
      >
        {props.data.count}{" "}
      </span>
    </components.Option>
  );
};

此处 live example 您的代码已更新。