如何基于Ant Design实现动态增减双输入框并存储数据到数组
Hey there! Let's get that dynamic input group functionality working smoothly with Ant Design. I've revised your code to handle adding/removing input pairs and collecting the data into the array format you need. Here's the complete implementation:
import React, { useState } from "react"; import ReactDOM from "react-dom"; import "antd/dist/antd.css"; import { Form, Input, Button } from "antd"; function DualInput({ form }) { const { getFieldDecorator } = form; // Track each input group with a unique ID to avoid field name conflicts const [inputGroups, setInputGroups] = useState([{ id: 0 }]); // Store the final submitted data array const [submittedData, setSubmittedData] = useState([]); const handleSubmit = (e) => { e.preventDefault(); form.validateFieldsAndScroll((err, fields) => { if (!err) { // Map through input groups to build the required array structure const formattedData = inputGroups.map(group => ({ Quantity: fields[`quantity_${group.id}`] || "", price: fields[`price_${group.id}`] || "" })); setSubmittedData(formattedData); console.log("Final submitted data:", formattedData); } }); }; const handleAdd = () => { // Add a new input group with a unique timestamp ID setInputGroups([...inputGroups, { id: Date.now() }]); }; const handleMinus = (groupId) => { // Remove the target group, but keep at least one group if (inputGroups.length > 1) { setInputGroups(inputGroups.filter(group => group.id !== groupId)); } }; return ( <div> <Form layout="inline" onSubmit={handleSubmit}> {/* Render each input group dynamically */} {inputGroups.map((group, index) => ( <div key={group.id} style={{ marginBottom: 16, display: "flex", alignItems: "center" }}> <Form.Item label={`Quantity ${index + 1}`}> {getFieldDecorator(`quantity_${group.id}`, { rules: [{ required: true, message: "Please enter a quantity!" }] })(<Input placeholder="Quantity" size="large" />)} </Form.Item> <Form.Item label={`Price ${index + 1}`}> {getFieldDecorator(`price_${group.id}`, { rules: [{ required: true, message: "Please enter a price!" }] })(<Input placeholder="Price" size="large" />)} </Form.Item> <Form.Item> <Button type="secondary" shape="circle" icon="minus" size="large" onClick={() => handleMinus(group.id)} disabled={inputGroups.length === 1} /> </Form.Item> </div> ))} {/* Add new group button */} <Form.Item> <Button type="secondary" shape="circle" icon="plus" size="large" onClick={handleAdd} /> </Form.Item> {/* Submit button */} <Form.Item> <Button type="primary" size="large" htmlType="submit">Submit</Button> </Form.Item> </Form> {/* Optional: Display submitted data for verification */} {submittedData.length > 0 && ( <div style={{ marginTop: 20, padding: 10, border: "1px solid #eee" }}> <h4>Submitted Data:</h4> <pre style={{ margin: 0 }}>{JSON.stringify(submittedData, null, 2)}</pre> </div> )} </div> ); } const DualInput2 = Form.create()(DualInput); ReactDOM.render(<DualInput2 />, document.getElementById("container"));
Key Changes & Explanations:
- State for Input Groups: We use
inputGroupsstate to track each pair of inputs, with a uniqueidfor each group to prevent field name collisions. - Dynamic Field Names: Each input uses a unique name like
quantity_${group.id}so Ant Design's Form can distinguish between different groups. - Add/Remove Logic:
handleAddadds a new group with a timestamp-based ID (guaranteed unique).handleMinusremoves the specific group by ID, and disables when only one group remains to avoid empty state.
- Form Submission: After validation, we map through the input groups to extract data into your desired array format, then store it in
submittedDatastate. - Validation: Added required rules to ensure users fill out all fields before submitting.
内容的提问来源于stack exchange,提问作者user9891825
相关产品推荐
相关产品推荐

