React App - Multi Select

背景

antdreact-select其实都有多选和添加新元素功能, 但是不太好用的是如果选择了多项以后的展示会堆叠, 删除操作也比较复杂, 所以我们这边需要开发一个更友好的多选组件

开发过程

最终效果

这里先把最终结果放上来与antd的对比一下, 证明用三天时间开发这个组件还是非常有意义的

  • antd的多选组件
  • 自己开发的多选组件

而且支持虚拟滚动/创建选项/全选/清空/模糊搜索等功能, 可以说是全方位超过antd的多选组件了

组件设计

组件设计本来是分为两个部分: 选择器和下拉弹出框, 但是后来开发的时候发现还需要一个比较通用的checkbox组件, 所以单独实现了一个span-checkbox组件

选择器

用于展示选择项和触发下拉弹窗的控件, 实现起来也比较简单, 基本就是纯粹的div元素和样式设置, 不过这里参考了antd-select, 使用RcTrigger作为触发器, 可以省去实现下拉框弹出收起的动画的代码, 实现和antd相同的动画

组件的传参也基本完全参照antd-select的传参, 只是为了偷懒, 没有额外实现下拉项的Options子组件解析, 只支持options传参

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import React, { useState, useMemo, useRef, useLayoutEffect } from 'react';
import RcTrigger from 'rc-trigger';
import classNames from 'classnames';
import { SelectProps } from 'antd/lib/select';
import { DownOutlined, CloseOutlined, LoadingOutlined } from '@ant-design/icons';
import { useUpdate, useTranslation } from '../../use';
import MultiSelectPopup from './popup';

const placements = {
// Enable horizontal overflow auto-adjustment when a custom dropdown width is provided
bottomLeft: {
points: ['tl', 'bl'],
offset: [0, 4],
overflow: {
adjustX: 1,
adjustY: 1,
},
},
topLeft: {
points: ['bl', 'tl'],
offset: [0, -4],
overflow: {
adjustX: 1,
adjustY: 1,
},
},
};

const MIN_POPUP_WIDTH = 200;

export type MultiOptionType<T extends string | number> = { value: T; label: React.ReactNode; data?: any };

export type MultiSelectProps<T extends string | number> = Pick<
SelectProps<T[]>,
| 'className'
| 'disabled'
| 'dropdownClassName'
| 'dropdownRender'
| 'getPopupContainer'
| 'mode'
| 'placeholder'
| 'showArrow'
| 'showSearch'
| 'value'
| 'onDropdownVisibleChange'
| 'open'
> & {
/**
* 如果 mode === tag, 且value是number类型, 此值需要设置为true
*/
valueIsNumber?: boolean;
searchPlaceholder?: string;
loading?: boolean;
onChange: (value: T[]) => void;
options: MultiOptionType<T>[];
filterOption?: (inputValue: string, option: MultiOptionType<T>) => boolean;
};

export type MultiSelectComponent<T extends string | number> = React.FC<MultiSelectProps<T>>;

const MultiSelect: {
<T extends string | number = string>(...args: Parameters<MultiSelectComponent<T>>): ReturnType<MultiSelectComponent<T>>;
} = <T extends string | number = string>({
className,
disabled = false,
dropdownClassName,
dropdownRender,
filterOption,
getPopupContainer,
mode = 'multiple',
placeholder,
showArrow = true,
showSearch = true,
valueIsNumber = false,
searchPlaceholder = 'Search...',
loading = false,
value,
onDropdownVisibleChange,
onChange,
open = false,
options = [],
}: Parameters<MultiSelectComponent<T>>[0]) => {
const t = useTranslation();

const [focusState, setFocusState] = useState(open);
const [openState, setOpenState] = useState(open);
useUpdate(() => {
if (open !== openState) {
setOpenState(open);
}
}, [open]);

const changeVisiable = (visiable: boolean) => {
setOpenState(visiable);
onDropdownVisibleChange && onDropdownVisibleChange(visiable);
};

const selectedOptions = useMemo(() => {
const optionsMap = _.mapKeys(options, 'value');
return _.map(value, (x) => optionsMap[x] || { label: x, value: x });
}, [options, value]);

const triggerDivRef = useRef<HTMLDivElement>(null);
const [popupWidthState, setPopupWidthState] = useState(MIN_POPUP_WIDTH);

useLayoutEffect(() => {
if (openState) {
setPopupWidthState(_.max([triggerDivRef.current.clientWidth, MIN_POPUP_WIDTH]));
}
}, [openState]);

return (
<RcTrigger
builtinPlacements={placements}
popupPlacement='bottomLeft'
popupTransitionName='slide-up'
action={disabled || loading ? [] : ['click']}
popupClassName={classNames('padding-0', dropdownClassName)}
prefixCls='ant-select-dropdown'
getPopupContainer={getPopupContainer}
popupVisible={openState}
onPopupVisibleChange={changeVisiable}
popup={
<MultiSelectPopup<T>
value={value}
open={openState}
onChange={onChange}
create={mode === 'tags'}
searchPlaceholder={searchPlaceholder}
options={options}
width={popupWidthState}
valueIsNumber={valueIsNumber}
showSearch={showSearch}
filterOption={filterOption}
/>
}
>
<div
className={classNames(`ant-select ant-select-multiple multi-select`, className, {
'ant-select-focused': focusState || openState,
'ant-select-open': openState,
'ant-select-disabled': disabled,
'ant-select-show-arrow': showArrow,
'ant-select-show-search': showSearch,
})}
ref={triggerDivRef}
tabIndex={0}
onFocus={() => setFocusState(true)}
onBlur={() => setFocusState(false)}
>
<div className='ant-select-selector'>
{placeholder && selectedOptions.length === 0 && <span className='ant-select-selection-placeholder'>{placeholder}</span>}
{selectedOptions.length > 0 &&
selectedOptions.length <= 2 &&
selectedOptions.map((option) => (
<span className='ant-select-selection-item' key={option.value}>
<span className='ant-select-selection-item-content'>{option.label}</span>
<span
className='ant-select-selection-item-remove'
onClick={(event) => {
event.stopPropagation();
onChange(value.filter((x) => x !== option.value));
}}
>
<CloseOutlined />
</span>
</span>
))}
{selectedOptions.length > 2 && (
<span className='ant-select-selection-item'>
<span className='ant-select-selection-item-content'>
{t('MULTI_SELECT_LABEL_SELECTED_ITEM_PREFIX')}
<span className='multi-select-popup-options-selected-tips-num'>{selectedOptions.length}</span>
{t('MULTI_SELECT_LABEL_SELECTED_ITEM_SUFFIX')}
</span>
</span>
)}
{loading ? (
<span className='ant-select-arrow ant-select-arrow-loading'>
<LoadingOutlined />
</span>
) : null}
{!loading && showArrow ? (
<span className='ant-select-arrow'>
<DownOutlined />
</span>
) : null}
</div>
<style jsx global>{`
.multi-select {
outline: 0;
&.ant-select-show-search {
&.ant-select-multiple {
.ant-select-selector {
cursor: pointer;
flex-wrap: nowrap;
overflow: hidden;
.ant-select-selection-item {
flex-shrink: 1;
flex-grow: 0;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
cursor: pointer;
}
}
}
&.ant-select-allow-clear,
&.ant-select-show-arrow {
.ant-select-selector {
padding-right: 24px;
.ant-select-selection-placeholder {
margin-right: 13px;
}
}
}
}
min-width: 30px;
}
`}</style>
</div>
</RcTrigger>
);
};

export default MultiSelect;

下拉弹出框

因为使用了RcTriggerpopup作为展示容器, 所以弹出框里面只需要实现自己的样式就行

左右两边的下拉列表都需要使用虚拟滚动实现, 否则在数据量较大的情况下会有卡顿感
用虚拟滚动实现后, 实测10万下拉数据的全选和过滤都不会有卡顿感
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import React, { useRef, useState, useMemo, useLayoutEffect } from 'react';
import { Checkbox, Button } from 'antd';
import { FixedSizeList, areEqual, ListChildComponentProps } from 'react-window';
import classNames from 'classnames';
import { SearchOutlined, DeleteOutlined, CloseOutlined } from '@ant-design/icons';
import { MultiOptionType } from './multi-select';
import { useTranslation } from '../../use';

export type MultiSelectPopupProps<T extends string | number> = {
showSearch?: boolean;
searchPlaceholder?: string;
create?: boolean;
value: T[];
open: boolean;
onChange: (value: T[]) => void;
options: MultiOptionType<T>[];
filterOption?: (inputValue: string, option: MultiOptionType<T>) => boolean;
width: number;
onClick?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
listItemHeight?: number;
listHeight?: number;
/**
* 如果 mode === tag, 且value是number类型, 此值需要设置为true
*/
valueIsNumber?: boolean;
};

export type MultiSelectPopupComponent<T extends string | number> = React.FC<MultiSelectPopupProps<T>>;

const MultiSelectPopup: {
<T extends string | number>(...args: Parameters<MultiSelectPopupComponent<T>>): ReturnType<MultiSelectPopupComponent<T>>;
} = <T extends string | number>({
showSearch = true,
searchPlaceholder = '',
create = false,
value,
open,
onChange,
options,
filterOption,
width,
onClick,
listItemHeight = 32,
listHeight = 320,
valueIsNumber = false,
}: Parameters<MultiSelectPopupComponent<T>>[0]) => {
const t = useTranslation();

const [showSelectedOptionsState, setShowSelectedOptionsState] = useState(true);
const [searchValueState, setSearchValueState] = useState('');

const _changeItemFnRef = useRef((item: T, operate: 'add' | 'remove') => {
onChange(operate === 'add' ? value.concat(item) : value.filter((x) => x !== item));
});
_changeItemFnRef.current = (item: T, operate: 'add' | 'remove') => {
onChange(operate === 'add' ? value.concat(item) : value.filter((x) => x !== item));
};

const filterOptions = useMemo(() => {
const _filterFn =
filterOption ||
((inputValue: string, option: MultiOptionType<T>) =>
!inputValue ||
_.toLower(_.toString(option.label)).includes(_.toLower(inputValue)) ||
_.toLower(_.toString(option.value)).includes(_.toLower(inputValue)));
const _searchInputValue = _.trim(searchValueState);
const filterOptions = _.filter(options, (option) => _filterFn(_searchInputValue, option));
if (_searchInputValue && !_.find(filterOptions, (option) => option.value === _searchInputValue) && create) {
filterOptions.push({ label: _searchInputValue, value: (valueIsNumber ? _.toNumber(_searchInputValue) : _searchInputValue) as T });
}
return filterOptions;
}, [options, searchValueState, filterOption]);

const { checkStateFilterOptions, checkedAllOptions } = useMemo(() => {
const checkStateFilterOptions = _.map(filterOptions, (x) => ({ ...x, checked: _.includes(value, x.value) }));
return { checkStateFilterOptions, checkedAllOptions: _.every(checkStateFilterOptions, (item) => item.checked) };
}, [filterOptions, value]);

const selectedOptions = useMemo(() => {
const optionsMap = _.mapKeys(options, 'value');
return _.map(value, (x) => optionsMap[x] || { label: x, value: x });
}, [options, value]);

// fix: need calc input item height
const minListHeight = _.min([listHeight, _.max([filterOptions.length * listItemHeight, selectedOptions.length * listItemHeight])]);

const OptionRow = useMemo(
() =>
React.memo((props: ListChildComponentProps) => {
const { index, style, data } = props;
return (
<div className='ant-select-item ant-select-item-option' style={style} title={data[index].label}>
<Checkbox
className='ant-select-item-option-content'
checked={data[index].checked}
onChange={(event) => _changeItemFnRef.current(data[index].value, event.target.checked ? 'add' : 'remove')}
>
{data[index].label}
</Checkbox>
</div>
);
}, areEqual),
[],
);
const SelectedOptionRow = useMemo(
() =>
React.memo((props: ListChildComponentProps) => {
const { index, style, data } = props;
return (
<div className='ant-select-item ant-select-item-option' style={style}>
<Button
className='ant-select-item-option-selected-remove-btn'
size='small'
onClick={() => _changeItemFnRef.current(data[index].value, 'remove')}
title={data[index].label}
>
<span className='ant-select-item-option-selected-remove-btn-label'>{data[index].label}</span>
<CloseOutlined className='ant-select-item-option-selected-remove-btn-icon' />
</Button>
</div>
);
}, areEqual),
[],
);

const inputRef = useRef<HTMLInputElement>(null);
useLayoutEffect(() => {
if (open && inputRef.current) {
inputRef.current.focus();
}
}, [open]);

return (
<div className='multi-select-popup' style={{ width: showSelectedOptionsState ? width * 2 : width }} onClick={onClick}>
{showSearch && (
<div className='multi-select-popup-search-bar'>
<SearchOutlined className='multi-select-popup-search-icon' />
<input
ref={inputRef}
className='multi-select-popup-search-input ant-input'
value={searchValueState}
onChange={(event) => setSearchValueState(event.target.value)}
placeholder={searchPlaceholder}
/>
</div>
)}
<div className='multi-select-popup-body'>
<div className='multi-select-popup-left-content' style={{ width: width }}>
<div className='multi-select-popup-options-control-bar'>
<Checkbox
disabled={checkStateFilterOptions.length === 0}
checked={checkStateFilterOptions.length > 0 && checkedAllOptions}
onChange={(event) =>
onChange(
event.target.checked
? _.union(
value,
checkStateFilterOptions.map((x) => x.value),
)
: _.difference(
value,
checkStateFilterOptions.map((x) => x.value),
),
)
}
>
{t('MULTI_SELECT_LABEL_SELECT_ALL')}
</Checkbox>
<Checkbox checked={showSelectedOptionsState} onChange={(event) => setShowSelectedOptionsState(event.target.checked)}>
{t('MULTI_SELECT_LABEL_VIEW_SELECTED_ITEM')}
</Checkbox>
</div>
<div className='multi-select-popup-options-list'>
<FixedSizeList
height={minListHeight}
itemCount={checkStateFilterOptions.length}
itemSize={listItemHeight}
width={width}
itemData={checkStateFilterOptions}
>
{OptionRow}
</FixedSizeList>
</div>
</div>
<div className={classNames('multi-select-popup-right-content', { hide: !showSelectedOptionsState })} style={{ width: width }}>
<div className='multi-select-popup-options-control-bar'>
<span className='multi-select-popup-options-selected-tips'>
{t('MULTI_SELECT_LABEL_SELECTED_ITEM_PREFIX')}
<span className='multi-select-popup-options-selected-tips-num'>{value.length}</span>
{t('MULTI_SELECT_LABEL_SELECTED_ITEM_SUFFIX')}
</span>
<Button className='multi-select-popup-options-remove-all-btn' size='small' type='link' danger onClick={() => onChange([])}>
<DeleteOutlined />
</Button>
</div>
<div className='multi-select-popup-selected-options-list'>
<FixedSizeList
height={minListHeight}
itemCount={selectedOptions.length}
itemSize={listItemHeight}
width={width}
itemData={selectedOptions}
>
{SelectedOptionRow}
</FixedSizeList>
</div>
</div>
</div>
<style jsx global>{`
// 样式比较长, 此处省略
`}</style>
</div>
);
};

export default MultiSelectPopup;

checkbox

这里就是简单的封装了一个带labelcheckbox, 并且样式直接复用了antdclass, 开发成本较低

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import React from 'react';
import classNames from 'classnames';
import { CheckboxProps } from 'antd/lib/checkbox';

const SpanCheckbox: React.FC<CheckboxProps> = ({
prefixCls = 'ant',
className,
children,
indeterminate = false,
style,
onMouseEnter,
onMouseLeave,
checked,
disabled,
id,
onChange,
}) => {
const clickChangeChecked = (event: React.MouseEvent<HTMLLabelElement, MouseEvent>) => {
if (disabled) {
return;
}
onChange({
target: {
checked: !checked,
},
stopPropagation() {
event.stopPropagation();
},
preventDefault() {
event.preventDefault();
},
nativeEvent: event.nativeEvent,
});
};
return (
<label
className={classNames(className, {
[`${prefixCls}-checkbox-wrapper`]: true,
[`${prefixCls}-checkbox-wrapper-checked`]: checked,
[`${prefixCls}-checkbox-wrapper-disabled`]: disabled,
})}
style={style}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
onClick={clickChangeChecked}
>
<span
className={classNames(`${prefixCls}-checkbox`, {
[`${prefixCls}-checkbox-indeterminate`]: indeterminate,
[`${prefixCls}-checkbox-checked`]: checked,
[`${prefixCls}-checkbox-disabled`]: disabled,
})}
>
<span id={id} className={`${prefixCls}-checkbox-input`} />
<span className={`${prefixCls}-checkbox-inner`} />
</span>
{children !== undefined && <span>{children}</span>}
</label>
);
};

export default SpanCheckbox;

小结

此基础组件开发完成后是提供全局使用的, 从antd-select切换过来的成本也极低, 开发完成后项目内的所有多选组件都已经替换为此组件了, 性价比还是比较高的

作者

Mosby

发布于

2020-04-10

许可协议

评论