feat(select): 支持排除和包含选项的过滤功能
- 在组件中新增 exclude 和 include 属性,支持对数据进行筛选 - 使用 useMemo 优化实际展示数据的计算逻辑 - 引入工具函数 getMatchedItems 和 getUnmatchedItems 进行数据过滤 - 修改回调函数和 options 渲染为基于过滤后的数据 - 通过 onGetData 返回过滤后的数据列表1.0
parent
0942217014
commit
a20ccba63c
|
|
@ -21,6 +21,10 @@ export interface BasicSelectProps extends SelectProps {
|
|||
onGetData?: (data: Record<string, any>[]) => void;
|
||||
/** 自定义 label 的渲染函数 */
|
||||
labelRender?: (item: Record<string, any>) => ReactNode;
|
||||
/** 排除的项 */
|
||||
exclude?: string[];
|
||||
/** 包含的项 */
|
||||
include?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { Select } from "antd";
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { getMatchedItems, getUnmatchedItems } from "../../../utils";
|
||||
|
||||
/**
|
||||
* 基础下拉组件
|
||||
|
|
@ -15,9 +16,25 @@ function BasicSelect(props) {
|
|||
nameKey = "name",
|
||||
idKey = "id",
|
||||
labelRender,
|
||||
exclude = [],
|
||||
include = [],
|
||||
...restProps
|
||||
} = props;
|
||||
|
||||
const actualData = useMemo(() => {
|
||||
let result = data;
|
||||
|
||||
if (exclude.length > 0) {
|
||||
result = getUnmatchedItems({ list: result, value: exclude, idKey });
|
||||
}
|
||||
|
||||
if (include.length > 0) {
|
||||
result = getMatchedItems({ list: result, value: include, idKey });
|
||||
}
|
||||
|
||||
return result;
|
||||
}, [data, exclude, include, idKey]);
|
||||
|
||||
const handleChange = (event, option) => {
|
||||
if (onGetLabel || onGetOption) {
|
||||
if (Array.isArray(event)) {
|
||||
|
|
@ -25,7 +42,7 @@ function BasicSelect(props) {
|
|||
const findItems = [];
|
||||
const names = [];
|
||||
event.forEach((item) => {
|
||||
const findItem = data.find(dataItem => dataItem[idKey] === item);
|
||||
const findItem = actualData.find(dataItem => dataItem[idKey] === item);
|
||||
if (findItem) {
|
||||
findItems.push(findItem);
|
||||
names.push(findItem[nameKey]);
|
||||
|
|
@ -41,7 +58,7 @@ function BasicSelect(props) {
|
|||
}
|
||||
else {
|
||||
if (event) {
|
||||
const findItem = data.find(item => item[idKey] === event);
|
||||
const findItem = actualData.find(item => item[idKey] === event);
|
||||
onGetLabel?.(findItem[nameKey]);
|
||||
onGetOption?.(findItem);
|
||||
}
|
||||
|
|
@ -55,12 +72,12 @@ function BasicSelect(props) {
|
|||
};
|
||||
|
||||
useEffect(() => {
|
||||
onGetData?.(data);
|
||||
}, [data]);
|
||||
onGetData?.(actualData);
|
||||
}, [actualData]);
|
||||
|
||||
return (
|
||||
<Select placeholder={`请选择${placeholder}`} showSearch allowClear optionFilterProp="children" onChange={handleChange} {...restProps}>
|
||||
{data.map((item) => {
|
||||
{actualData.map((item) => {
|
||||
const value = item[idKey];
|
||||
const label = labelRender ? labelRender(item) : item[nameKey];
|
||||
return (
|
||||
|
|
|
|||
Loading…
Reference in New Issue