【问题标题】:How to get filtered options in MenuList?如何在 MenuList 中获取过滤选项?
【发布时间】:2019-10-25 10:00:46
【问题描述】:

我正在尝试为react-select 构建一个“全部插入”到自定义MenuList 组件中。

看起来像这样:

const MySelect = (props) => {

  const MenuList = ({ children, ...ownProps }) => {
    return (
      <div>
        <button onClick={() => ownProps.setValue(props.options)}>
          Insert all
        </button>
        <components.MenuList {...ownProps}>{children}</components.MenuList>
      </div>
    );
  };

  return (
    <ReactSelect options={props.options} components={{ MenuList }} ... />
  );
}

问题:options 仅包含所有选项,在用户开始输入可搜索选择之前。

开始输入后,假设剩下 50 个选项中的 5 个。

当有人点击Insert all 时,我只想插入剩下的 5 个选项。但是所有 50 个选项都被插入。我检查了ownProps 是否有类似filteredOptions 的东西,但那并不存在。有什么办法可以得到过滤后的选项?

【问题讨论】:

标签: react-select


【解决方案1】:

看起来react-select 不提供此类信息。您必须自己实现这一目标。尝试在 react-select 库上编写可过滤状态。

【讨论】:

    【解决方案2】:

    让它工作,但这远非理想:-/

    ...
      onClick={() => {
        const visibleOptions = props.options.filter(
          optionContainsStr(ownProps.selectProps.inputValue)
        );
    
        ownProps.setValue(visibleOptions);
      }}
    ...
    
    const optionContainsStr = str => option => {
      return (
        option.value
          .toString()
          .toLowerCase()
          .includes(str) || 
        option.label
          .toLowerCase()
          .includes(str)
      );
    };
    

    【讨论】:

    • 你显然做错了什么。因为这种简单的功能可以比您实现的方式简单得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-22
    • 2017-06-05
    • 1970-01-01
    相关资源
    最近更新 更多