在反应选择中显示没有嵌套选项的组的选择组名称

我正在使用组件react-select

    <Select
      options={transformedDataWithSubItems}
      value={selectedItem}
      onChange={handleChange}
      isClearable={isClearable}
      placeholder={placeholder}
    />

transformedDataWithSubItems 看起来像这样:

const transformedDataWithSubItems = [
  { id: 1, label: "1", options: [{ label: 'sub', value: 'sub' }, { label: 'sub', value: 'sub' }] },
  { id: 3, label: "2", options: [{ label: 'sub', value: 'sub' }, { label: 'sub', value: 'sub' }] },
  { id: 5, label: "3", options: [] }
];

有些类别没有项目(标签 3)。选择组件不显示这样的类别,我该如何解决?我需要显示没有元素的类别名称。

在此处输入图像描述


哆啦的时光机
浏览 114回答 1
1回答

红颜莎娜

如果没有嵌套选项,则需要删除该options属性。更改{ id: 5, label: "3", options: [] }=>{ id: 5, label: "3" }const transformedDataWithSubItems = [&nbsp; &nbsp; &nbsp; { id: 1, label: "1", options: [{ label: 'sub', value: 'sub' }, { label: 'sub', value: 'sub' }] },&nbsp; &nbsp; &nbsp; { id: 3, label: "2", options: [{ label: 'sub', value: 'sub' }, { label: 'sub', value: 'sub' }] },&nbsp; &nbsp; &nbsp; { id: 5, label: "3", options: [] }&nbsp; &nbsp; ].map(category => {&nbsp; &nbsp; &nbsp; if (category.options.length === 0) return {id: category.id, label: category.label};&nbsp; &nbsp; &nbsp; return category;&nbsp; &nbsp; });编辑: 如果你想让它显示为类别,那么你必须在选项中至少有一个元素。因此,在选项中添加一个元素并将其禁用。要做到这一点添加{ label: 'No sub category', disabled: true }const transformedDataWithSubItems = [&nbsp;{&nbsp; &nbsp;id: 1,&nbsp; &nbsp;label: '1',&nbsp; &nbsp;options: [&nbsp; &nbsp; &nbsp;{ label: 'sub', value: 'sub' },&nbsp; &nbsp; &nbsp;{ label: 'sub', value: 'sub' },&nbsp; &nbsp;],&nbsp;},&nbsp;{&nbsp; &nbsp;id: 3,&nbsp; &nbsp;label: '2',&nbsp; &nbsp;options: [&nbsp; &nbsp; &nbsp;{ label: 'sub', value: 'sub' },&nbsp; &nbsp; &nbsp;{ label: 'sub', value: 'sub' },&nbsp; &nbsp;],&nbsp;},&nbsp;{ id: 5, label: '3', options: [] },].map((category) => {&nbsp;if (category.options.length === 0) {&nbsp; &nbsp;return { ...category, options: [{ label: 'No sub category', disabled: true }]};&nbsp;}&nbsp;return category;});添加isOptionDisabled道具以选择组件。&nbsp;<Select&nbsp; &nbsp;options={transformedDataWithSubItems}&nbsp; &nbsp;value={selectedItem}&nbsp; &nbsp;onChange={handleChange}&nbsp; &nbsp;isClearable={isClearable}&nbsp; &nbsp;placeholder={placeholder}&nbsp; &nbsp;isOptionDisabled={(option) => option.disabled}&nbsp;/>见例子
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript