React-select isMulti选择所有过滤选项

时间:2019-08-28 19:24:01

标签: javascript reactjs react-select

我需要在多选中添加“全选”选项。如果至少有1个过滤选项,则应显示它。点击“全选”,然后应将已过滤的选项(不一定是所有选项)添加到已选择的选项

  1. 输入为空,因此所有选项都被“过滤”: enter image description here

单击全选选项,然后将所有选项添加到所选选项。

  1. 输入包含“ custom”,因此仅保留一个选项: enter image description here

然后单击“全选”选项,只会将该一个选项添加到所选选项中。

添加所有初始选项的“全选”选项很容易,但这并不是解决我的问题的方法。我设法通过手动过滤选项并将其过滤后以组件的状态存储来部分解决了我的问题,但我希望有一个更简单的解决方案。

1 个答案:

答案 0 :(得分:1)

我会使用s=pd.concat(l,keys=range(1,len(l)+1),axis=1).T.rename_axis('value').reset_index() table=table.merge(s).assign(result=lambda x : x['Match Rating']*x['rating']+x['const']) Out[732]: col1 col2 rating value const Match Rating result 0 England France 2 1 50.0 2.0 54.0 1 USA Spain 4 1 50.0 2.0 58.0 2 Germany Italy -5 2 48.0 2.0 38.0 3 Canada Jamaica 2 2 48.0 2.0 52.0 4 Cuba Bulgaria 1 3 47.0 2.5 49.5 5 Vietnam South Korea 2 3 47.0 2.5 52.0 filterOptionInputChange道具的组合:

  • onChange中,您每次用户更改InputChange并将其存储到状态时都会捕获inputValue。此值将在onChange中重用。
  • 您需要更改首字母filterOption才能始终显示Select all。原始逻辑是选项标签或值中是否包含inputValuenull返回true否则返回trueinputValue。在执行此逻辑之前,我们还有另一个条件,如果选项值对应于您的Select all选项,则立即返回true
  • onChange中;默认情况下,返回的选项是收到的选项。然后,如果选择了一个选项(可以删除多个选项),并且此选项为Select all,则返回的值应该是所有选项的副本,并由inputValue进行过滤。

也许有最简单的方法可以做到这一点,但我认为这非常有效:

onChange = (opt, { option }) => {
  let newOpts = opt;
  let string = this.state.searchField;

  if (option && option.value === "all") {
    let filteredOptions = clone(options);

    filteredOptions = filteredOptions.filter(
      filteredOption =>
        isIncludingString(string, filteredOption) &&
        !newOpts.includes(filteredOption)
    );

    string = null;
    newOpts = newOpts
      .concat(filteredOptions)
      .filter(newOpt => newOpt.value !== "all");
  }
  this.setState({
    searchField: string,
    values: newOpts
  });
};

onInputChange = (string, { action }) => {
  if (action === "input-change") {
    this.setState({
      searchField: string
    });
  }
};  

filterOption = ({ label, value }, string) => {
  if (value === "all") {
    return true;
  } else if (string) {
    return label.includes(string) || value.toString().includes(string);
  } else {
    return true;
  }
};
  

重要说明,在我的示例中,我使用clone中的lodash

isIncludingString中使用的onChange函数下面。

function isIncludingString(string, option) {
  let result = false;
  if (
    !string ||
    option.label.toString().includes(string) ||
    option.value.toString().includes(string)
  ) {
    result = true;
  }
  return result;
}

这里是live example