Dynamic Form Creation in React: A Comprehensive Guide
To create a dynamic form in React, you'll need to use state to store the values of the input fields and update them as the user types. You'll also need to use the 'map' method to dynamically generate the form fields based on an array of data.
Here's an example of how you can create a dynamic form with two input fields ('name' and 'email'):
import React, { useState } from 'react';
function DynamicForm() {
const [fields, setFields] = useState([
{ name: '', email: '' }
]);
const handleSubmit = (e) => {
e.preventDefault();
console.log(fields);
}
const handleChange = (e, index) => {
const { name, value } = e.target;
const newFields = [...fields];
newFields[index][name] = value;
setFields(newFields);
}
const handleAddField = () => {
setFields([...fields, { name: '', email: '' }]);
}
const handleRemoveField = (index) => {
const newFields = [...fields];
newFields.splice(index, 1);
setFields(newFields);
}
return (
<form onSubmit={handleSubmit}>
{fields.map((field, index) => (
<div key={index}>
<label>Name:</label>
<input
type="text"
name="name"
value={field.name}
onChange={(e) => handleChange(e, index)}
/>
<label>Email:</label>
<input
type="email"
name="email"
value={field.email}
onChange={(e) => handleChange(e, index)}
/>
{index > 0 && (
<button type="button" onClick={() => handleRemoveField(index)}>
Remove Field
</button>
)}
</div>
))}
<button type="button" onClick={handleAddField}>
Add Field
</button>
<button type="submit">Submit</button>
</form>
);
}
export default DynamicForm;
This code creates a form with one initial field and allows the user to add or remove fields as needed. The 'fields' state stores an array of objects, each representing a form field with 'name' and 'email' properties. The 'handleChange' function updates the 'fields' state when the user types into the input fields. The 'handleSubmit' function logs the final 'fields' array to the console when the form is submitted. The 'handleAddField' and 'handleRemoveField' functions allow the user to add or remove fields dynamically. The 'map' method is used to generate the form fields based on the 'fields' array.
原文地址: https://www.cveoy.top/t/topic/oBHj 著作权归作者所有。请勿转载和采集!