乐闻世界logo
搜索文章和话题

How to make react- hook -form work with multiple forms in one page?

1个答案

1

Using react-hook-form in React projects to handle multiple forms on a single page is a common requirement, which can typically be implemented through the following approaches:

1. Using Multiple useForm Hooks

In React, each form can utilize a separate useForm instance. This ensures that state management for each form remains independent and does not interfere with one another.

jsx
import { useForm } from 'react-hook-form'; function MultiFormPage() { const { register: register1, handleSubmit: handleSubmit1 } = useForm(); const { register: register2, handleSubmit: handleSubmit2 } = useForm(); const onSubmitForm1 = data => { console.log('Form 1 Data:', data); }; const onSubmitForm2 = data => { console.log('Form 2 Data:', data); }; return ( <div> <form onSubmit={handleSubmit1(onSubmitForm1)}> <input {...register1('firstName')} placeholder="First Name" /> <input type="submit" /> </form> <form onSubmit={handleSubmit2(onSubmitForm2)}> <input {...register2('lastName')} placeholder="Last Name" /> <input type="submit" /> </form> </div> ); }

2. Using a Single useForm with Field Differentiation

In certain scenarios, if you want to manage data for multiple forms using a single form instance, you can employ naming conventions in field names to distinguish fields belonging to different forms. For example:

jsx
import { useForm } from 'react-hook-form'; function MultiFormPage() { const { register, handleSubmit, setValue, getValues } = useForm(); const onSubmit = data => { console.log('Collected Data:', data); }; return ( <div> <form onSubmit={handleSubmit(onSubmit)}> <input {...register('form1.firstName')} placeholder="First Name" /> <input {...register('form2.lastName')} placeholder="Last Name" /> <input type="submit" /> </form> </div> ); }

In this example, form1.firstName and form2.lastName are used as field names to differentiate fields across different forms.

3. Dynamic Forms

If the number or structure of forms may change at runtime, you can dynamically create an array of useForm instances:

jsx
import { useForm } from 'react-hook-form'; function DynamicForms() { const forms = [ useForm(), useForm(), // You can dynamically add more as needed ]; const submitHandler = index => data => { console.log(`Form ${index + 1} Data:`, data); }; return ( <div> {forms.map((form, index) => ( <form key={index} onSubmit={form.handleSubmit(submitHandler(index))}> <input {...form.register(`field${index}`)} placeholder={`Field ${index + 1}`} /> <input type="submit" /> </form> ))} </div> ); }

This approach is highly flexible and well-suited for handling complex dynamic form scenarios.

The above are several common strategies for managing multiple forms. Selecting the appropriate implementation based on specific requirements and scenarios is crucial.

2024年6月29日 12:07 回复

你的答案