zy-react-library/components/Select/Basic/index.js

76 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-11-06 09:38:23 +08:00
import { Select } from "antd";
import { useEffect } from "react";
2025-11-06 09:38:23 +08:00
/**
* 基础下拉组件不建议直接使用此组件二次继承使用
*/
function BasicSelect(props) {
const {
onGetData,
2025-11-06 16:31:49 +08:00
onChange,
2025-11-06 16:02:51 +08:00
onGetLabel,
2025-11-07 15:09:53 +08:00
onGetOption,
2025-11-06 09:38:23 +08:00
placeholder = "",
data = [],
nameKey = "name",
idKey = "id",
...restProps
} = props;
2025-11-06 16:31:49 +08:00
const handleChange = (event, option) => {
2025-11-07 14:49:16 +08:00
if (Array.isArray(event)) {
if (event.length > 0) {
2025-11-07 15:09:53 +08:00
const findItems = [];
const names = [];
2025-11-07 14:49:16 +08:00
event.forEach((item) => {
2025-11-07 15:09:53 +08:00
const findItem = data.find(dataItem => dataItem[idKey] === item);
if (findItem) {
findItems.push(findItem);
names.push(findItem[nameKey]);
}
2025-11-07 14:49:16 +08:00
});
2025-11-07 15:09:53 +08:00
onGetLabel?.(names);
onGetOption?.(findItems);
2025-11-07 14:49:16 +08:00
}
else {
onGetLabel?.([]);
2025-11-07 15:09:53 +08:00
onGetOption?.([]);
2025-11-07 14:49:16 +08:00
}
}
else {
2025-11-07 15:09:53 +08:00
if (event) {
const findItem = data.find(item => item[idKey] === event);
onGetLabel?.(findItem[nameKey]);
onGetOption?.(findItem);
}
else {
2025-11-07 14:49:16 +08:00
onGetLabel?.("");
2025-11-07 15:09:53 +08:00
onGetOption?.({});
}
2025-11-07 14:49:16 +08:00
}
2025-11-06 16:31:49 +08:00
onChange?.(event, option);
2025-11-06 16:28:49 +08:00
};
2025-11-06 16:02:51 +08:00
useEffect(() => {
onGetData?.(data);
}, [data]);
2025-11-06 09:38:23 +08:00
return (
2025-11-06 16:02:51 +08:00
<Select placeholder={`请选择${placeholder}`} showSearch allowClear onChange={handleChange} {...restProps}>
2025-11-06 09:38:23 +08:00
{data.map((item) => {
const value = item[idKey];
const label = item[nameKey];
return (
<Select.Option key={value} value={value}>
{label}
</Select.Option>
);
})}
</Select>
);
}
BasicSelect.displayName = "BasicSelect";
export default BasicSelect;