如何在每个下拉项下面使用react-select自定义渲染子文档?

问题描述 投票:0回答:1

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

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

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

react-select
1个回答
1
投票

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-select V1解决方案:

保持与V2解决方案相同的结构,您可以通过使用props 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

© www.soinside.com 2019 - 2024. All rights reserved.