在react-select中是否可以使用“全选/全选”选项? 这是内置的,还是我必须自己做?
答案 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)
您可以通过这种方式轻松实现:
https://medium.com/@alex_escalante/react-select-alloptionoptions-with-a-single-click-1ebf5a33fe31
答案 2 :(得分:1)