index.tsx
2.19 KB
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
import { UButton, UDatePicker, UForm, UFormItem, UInput, URadio, USelect } from '@uj/ui';
import type { FieldSchema } from '../formSchema';
export interface SearchFormProps<T extends Record<string, unknown>> {
fields: FieldSchema<T>[];
initialValues?: Partial<T>;
onSearch: (values: T) => void;
onReset?: (values: Partial<T>) => void;
}
export function SearchForm<T extends Record<string, unknown>>({
fields,
initialValues,
onSearch,
onReset,
}: SearchFormProps<T>) {
const [form] = UForm.useForm();
const control = (field: FieldSchema<T>) => {
const common = {
disabled: typeof field.disabled === 'boolean' ? field.disabled : false,
placeholder: field.placeholder,
};
const width = field.width ?? (field.type === 'input' || field.type === 'textarea' ? 260 : 160);
if (field.type === 'select' || field.type === 'selectMultiple')
return (
<USelect
{...common}
allowClear={false}
style={{ width }}
options={field.options}
mode={field.type === 'selectMultiple' ? 'multiple' : undefined}
/>
);
if (field.type === 'date') return <UDatePicker {...common} style={{ width }} />;
if (field.type === 'dateRange')
return <UDatePicker.RangePicker disabled={common.disabled} style={{ width }} />;
if (field.type === 'radio') return <URadio.Group {...common} options={field.options} />;
return field.type === 'textarea' ? (
<UInput.TextArea {...common} style={{ width }} />
) : (
<UInput {...common} style={{ width }} />
);
};
return (
<UForm
form={form}
initialValues={initialValues}
layout="inline"
onFinish={(values) => onSearch(values as T)}
>
{fields.map((field) => (
<UFormItem key={field.name} name={field.name as string} label={field.label}>
{control(field)}
</UFormItem>
))}
<UFormItem>
<UButton htmlType="submit">查询</UButton>
<UButton
type="default"
onClick={() => {
form.setFieldsValue(initialValues);
onReset?.(initialValues ?? {});
}}
>
重置
</UButton>
</UFormItem>
</UForm>
);
}