如何使用 react-select 在每个下拉项下方自定义呈现子文本?

How can I use react-select to custom render subtext below each dropdown item?

我正在尝试弄清楚如何利用 react-select 中的自定义组件来呈现包含带有子文本的项目的下拉菜单。

我查看了每个组件:https://react-select.com/components,但不确定哪一个最符合我的需要。

通过查看组件列表,我相信 option 组件是用于类似的东西并且可能会起作用,但我不确定。有人可以验证我的想法吗?

React-select V2+解决方案:

您完全正确,使用 Option 组件将允许您格式化 menuList 中的每个选项,如下例所示:

const options = [
  {
    label: "text 1",
    subLabel: "subtext 1",
    value: "1"
  },
  {
    label: "text 2",
    subLabel: "subtext 2",
    value: "2"
  },
  {
    label: "text 3",
    subLabel: "subtext 3",
    value: "3"
  },
  {
    label: "text 4",
    subLabel: "subtext 4",
    value: "4"
  }
];

const Option = props => {
  return (
    <components.Option {...props}>
      <div>{props.data.label}</div>
      <div style={{ fontSize: 12 }}>{props.data.subLabel}</div>
    </components.Option>
  );
};

function App() {
  return (
    <div className="App">
      <Select options={options} components={{ Option }} />
    </div>
  );
}

这里是live example.

React-selectV1解决方案:

保持与 V2 解决方案相同的结构,您可以通过使用道具 optionRenderer 传递渲染函数来实现显示自定义选项元素,如下所示:

class App extends Component {
  renderOption = option => (
    <div>
      <label>{option.label}</label>
      <label style={{ display: "block", color: "gray", fontSize: 12 }}>
        {option.subLabel}
      </label>
    </div>
  );
  render() {
    return (
      <div className="App">
        <Select options={options} optionRenderer={this.renderOption} />
      </div>
    );
  }
}

这里是live example.