Update useForm hooks supports input type checkbox

支持 checkbox,虽然只是返回 boolean,但这个判断和正常表单还是有区别的
This commit is contained in:
2024-04-25 11:32:52 +08:00
parent 6632c839e4
commit aec8c8ac7a
2 changed files with 29 additions and 15 deletions
+29 -6
View File
@@ -21,6 +21,10 @@ interface UseFormReturns<T extends defaultValues> {
onSubmit: (fn: (values: T) => void) => (ev: React.FormEvent) => void
}
const isCheckBox = (el: HTMLElement) => {
return el instanceof HTMLInputElement && el.type === "checkbox";
}
function useForm<T extends defaultValues>({ initialValues }: Props<T>) {
const inputs = useRef<Partial<Record<keyof T, InputElements>>>({});
const values = useRef<T>({ ...initialValues } as T);
@@ -32,10 +36,19 @@ function useForm<T extends defaultValues>({ initialValues }: Props<T>) {
}
const setValue = (name, value) => {
console.log(inputs.current[name], name);
const el = inputs.current[name];
if (inputs.current[name]) {
console.log(el, name);
if (el) {
values.current[name as keyof T] = value;
if (el instanceof HTMLInputElement && el.type === "checkbox") {
el.checked = value;
return;
}
inputs.current[name].value = value;
}
}
@@ -47,8 +60,6 @@ function useForm<T extends defaultValues>({ initialValues }: Props<T>) {
}
const bindInput = (name: string) => {
console.log('bindinput')
return {
name,
id: name,
@@ -57,11 +68,23 @@ function useForm<T extends defaultValues>({ initialValues }: Props<T>) {
if (target) {
inputs.current[name as keyof T] = target;
if (isCheckBox(target)) {
target.checked = initialValues?.[name];
}
else if (name in initialValues) {
target.value = initialValues[name];
}
}
},
defaultValue: initialValues[name],
onChange: (ev) => {
const { name, value } = ev.target;
const { name, value, checked } = ev.target;
if (isCheckBox(ev.target)) {
values.current[name as keyof T] = checked;
return;
}
values.current[name as keyof T] = value;
},