全选/取消全选选项

时间:2018-08-24 09:39:25

标签: reactjs react-select

在react-select中是否可以使用“全选/全选”选项? 这是内置的,还是我必须自己做?

3 个答案:

答案 0 :(得分:10)

在我工作的公司中,我们为react-select做了包装,并添加了一些其他功能和样式。功能之一是“全选/取消全选”。

这是指向该组件降级页面的链接:

https://topia.design/components/multi-select/

这是我用来实现“全选/取消全选”的方法:

https://codesandbox.io/s/distracted-panini-8458i?file=/src/MultiSelect.js

import React, { useRef } from "react";
import ReactSelect from "react-select";

export const MultiSelect = props => {
  // isOptionSelected sees previous props.value after onChange
  const valueRef = useRef(props.value);
  valueRef.current = props.value;

  const selectAllOption = {
    value: "<SELECT_ALL>",
    label: "All Items"
  };

  const isSelectAllSelected = () =>
    valueRef.current.length === props.options.length;

  const isOptionSelected = option =>
    valueRef.current.some(({ value }) => value === option.value) ||
    isSelectAllSelected();

  const getOptions = () => [selectAllOption, ...props.options];

  const getValue = () =>
    isSelectAllSelected() ? [selectAllOption] : props.value;

  const onChange = (newValue, actionMeta) => {
    const { action, option, removedValue } = actionMeta;

    if (action === "select-option" && option.value === selectAllOption.value) {
      props.onChange(props.options, actionMeta);
    } else if (
      (action === "deselect-option" &&
        option.value === selectAllOption.value) ||
      (action === "remove-value" &&
        removedValue.value === selectAllOption.value)
    ) {
      props.onChange([], actionMeta);
    } else if (
      actionMeta.action === "deselect-option" &&
      isSelectAllSelected()
    ) {
      props.onChange(
        props.options.filter(({ value }) => value !== option.value),
        actionMeta
      );
    } else {
      props.onChange(newValue || [], actionMeta);
    }
  };

  return (
    <ReactSelect
      isOptionSelected={isOptionSelected}
      options={getOptions()}
      value={getValue()}
      onChange={onChange}
      hideSelectedOptions={false}
      closeMenuOnSelect={false}
      isMulti
    />
  );
};

答案 1 :(得分:1)

答案 2 :(得分:1)

我从Alex的方法中得到启发,但是我更改了他的代码的某些部分。我准备了example,如果您仍然需要,可以进行检查。