首页 > 解决方案 > 如何使用 react-select 在每个下拉项下方自定义呈现子文本?

问题描述

我试图弄清楚如何利用 react-select 中的自定义组件来呈现包含带有潜文本的项目的下拉列表。

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

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

标签: reactjsreact-select

解决方案


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

这里有一个活生生的例子

React-select V1 解决方案:

保持与 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>
    );
  }
}

这里有一个活生生的例子


推荐阅读