【问题标题】:Using material-ui autocomplete with dividers使用带有分隔符的 material-ui 自动完成
【发布时间】:2020-06-30 09:48:53
【问题描述】:

有没有办法在 material-ui 自动完成选项之间添加分隔符?

我只找到了这种解决方法,但我认为这不是最好的方法:

const options = [
    {
      label: 'Opt 1',
      value: 'OPT1'
    },
    {
      label: 'Divider',
      value: 'DIV',
      isDivider: true
    },
    {
      label: 'Opt 2',
      value: 'OPT2'
    },
    {
      label: 'Opt 3',
      value: 'OPT3'
    }
  ];

...

  // used to remove the opacity of disabled items (in my case dividers)
  autocompleteOption: {
    '&[aria-disabled="true"]': {
      opacity: 1
    }
  }

...

<Autocomplete
    options={options}
    multiple
    getOptionLabel={(option) => option.label}
    getOptionSelected={(option, value) => isEqual(value, option)}
    classes={{
      option: classes.autocompleteOption
    }}
    getOptionDisabled={(option) => option.isDivider}
    renderOption={(option) => {
      if (option.isDivider) {
        return <Divider className={classes.divider} />;
      }

      return option.label;
     }}
     ...
 />

  • 在我需要分隔符的地方添加了 isDivider 选项
  • 添加了 getOptionDisabled 方法来禁用分隔选项
  • 添加了一些样式以消除禁用项目的不透明度(在我的例子中是分隔符)
  • 添加了 renderOption 以根据 isDivider 属性呈现分隔线

您还有其他想法吗?

感谢您的宝贵时间:)

【问题讨论】:

  • 只是想说我得到了同样的解决方案。

标签: reactjs material-ui


【解决方案1】:

与其创建一个虚拟选项,不如标记选项后面应该有一个分隔符?

例如,假设您想在第三个和第四个选项之间添加一个分隔符。第三个选项将isDivider 设置为true

options[2].isDivider = true

然后在renderOption中插入&lt;Divider /&gt;如下:

renderOption={(props, option: any) => (
  <>
    <Li {...props}>{option.title}</Li>
    {option.isDivider ? <Divider /> : null}
  </>
)}

【讨论】:

    猜你喜欢
    • 2021-09-06
    • 1970-01-01
    • 2023-03-24
    • 2021-02-16
    • 1970-01-01
    • 2020-12-14
    • 2020-07-30
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多