React Hook Form 是一个强大的库,用于管理 React 中的表单,提供出色的性能和灵活的 API。但是,在某些情况下,您可能希望创建一个行为与标准表单不完全相同的表单。有时,表单数据发生变化时需要自动提交。这对于需要实时验证和提交的表单特别有用,例如搜索表单或动态过滤界面。
比方说,我们有一个简单的电子邮件搜索表单。
import { useForm } from 'react-hook-form'; interface FormValues { content: string; email: string; } const SearchForm = () => { const { register, handleSubmit } = useForm<FormValues>(); const onSubmit = (data: FormValues) => { console.log('Form submitted:', data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> <div>Search by</div> <div> <label>Content:</label> <input {...register('content')} /> </div> <div> <label>Email:</label> <input {...register('email')} /> </div> </form> ); };
但是我们可能想删除“提交”按钮并在没有它的情况下提交数据。为此,我们可以创建一个自定义的可重用挂钩,该挂钩将在表单更改时自动提交表单。
import { debounce } from 'lodash'; import { useCallback, useEffect, useState } from 'react'; import { type UseFormWatch, type FieldValues, type UseFormTrigger, type Path } from 'react-hook-form'; interface AutoSubmitProps<T extends FieldValues> { trigger: UseFormTrigger<T>; watch: UseFormWatch<T>; excludeFields?: Path<T>[]; onSubmit: () => void; onValidationFailed?: () => void; debounceTime?: number; } /** * Automatically submit data when it's changed */ export const useAutoSubmit = <T extends FieldValues>({ trigger, watch, onSubmit, debounceTime = 500, excludeFields, onValidationFailed, }: AutoSubmitProps<T>) => { const [isSubmiting, setIsSubmiting] = useState(false); const debouncedSumbit = useCallback( debounce((submitFn: () => void) => { submitFn(); }, debounceTime), [], ); useEffect(() => { const subscription = watch((_data, info) => { if (info?.type !== 'change') return; if (info.name && excludeFields?.includes(info.name)) return; setIsSubmiting(true); trigger() .then((valid) => { if (valid) debouncedSumbit(onSubmit); else onValidationFailed?.(); }) .finally(() => setIsSubmiting(false)); }); return () => subscription.unsubscribe(); }, [watch, onSubmit]); return { isSubmiting }; };
当字段更改时,该钩子会自动触发表单验证。如果验证成功,它会取消提交以避免过多的请求。
import { useForm } from 'react-hook-form'; import { useAutoSubmit } from './useAutoSubmit'; interface FormValues { content: string; email: string; } const SearchForm = () => { const { register, handleSubmit, trigger, watch } = useForm<FormValues>(); const onSubmit = (data: FormValues) => { console.log('Form submitted:', data); }; useAutoSubmit({ trigger, watch, onSubmit: handleSubmit(onSubmit), }); return ( <form onSubmit={handleSubmit(onSubmit)}> <div>Search by</div> <div> <label>Content:</label> <input {...register('content')} /> </div> <div> <label>Email:</label> <input {...register('email')} /> </div> </form> ); };
useAutoSubmit 钩子简化了 React 应用程序中自动提交表单的过程。通过使用此挂钩,您可以确保您的表单始终与最新的用户输入保持同步,从而减少手动提交的需要并增强整体用户体验
片段源代码
以上是以react-hook-form自动提交表单的详细内容。更多信息请关注PHP中文网其他相关文章!