training_data/apps/web/src/components/models/taxonomy/taxonomy-select.tsx

68 lines
1.6 KiB
TypeScript
Raw Normal View History

2024-12-30 08:26:40 +08:00
import { Button, Select } from "antd";
2025-01-06 08:45:23 +08:00
import { api } from "@nice/client"
2024-09-10 10:31:24 +08:00
import { useEffect, useState } from "react";
// 定义组件的 props 类型
interface TaxonomySelectProps {
2024-12-30 08:26:40 +08:00
defaultValue?: string;
value?: string;
onChange?: (value: string) => void;
width?: number | string; // 修改类型,支持百分比
placeholder?: string;
extraOptions?: { value: string | undefined; label: string }[]; // 新增 extraOptions 属性
2024-09-10 10:31:24 +08:00
}
export default function TaxonomySelect({
2024-12-30 08:26:40 +08:00
defaultValue,
value,
onChange,
width = "100%", // 默认设置为 100%
placeholder = "选择分类",
extraOptions = [], // 默认值为空数组
2024-09-10 10:31:24 +08:00
}: TaxonomySelectProps) {
2024-12-30 08:26:40 +08:00
const { data: taxonomies, isLoading: isTaxLoading } =
api.taxonomy.getAll.useQuery({});
2024-09-10 10:31:24 +08:00
2024-12-30 08:26:40 +08:00
const [selectedValue, setSelectedValue] = useState<string | undefined>(
defaultValue
);
2024-09-10 10:31:24 +08:00
2024-12-30 08:26:40 +08:00
// 当 defaultValue 或 value 改变时,将其设置为 selectedValue
useEffect(() => {
if (value !== undefined) {
setSelectedValue(value);
} else if (defaultValue !== undefined) {
setSelectedValue(defaultValue);
}
}, [defaultValue, value]);
2024-09-10 10:31:24 +08:00
2024-12-30 08:26:40 +08:00
// 内部处理选择变化,并调用外部传入的 onChange 回调(如果有的话)
const handleChange = (newValue: string) => {
setSelectedValue(newValue);
if (onChange) {
onChange(newValue);
}
};
2024-09-10 10:31:24 +08:00
2024-12-30 08:26:40 +08:00
return (
<>
2024-09-10 10:31:24 +08:00
2024-12-30 08:26:40 +08:00
<Select
allowClear
value={selectedValue}
style={{ width }}
options={[
...(taxonomies?.map((tax) => ({
value: tax.id,
label: tax.name,
})) || []),
...extraOptions, // 添加额外选项
]}
loading={isTaxLoading}
placeholder={placeholder}
onChange={handleChange}
/>
</>
);
2024-09-10 10:31:24 +08:00
}