You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ReactJs多输入值拆分存多对象及动态输入功能优化问题咨询

相关示意图

问题根因

你当前的代码只定义了单个color和size状态存储输入值,页面上多个同名字段的修改都会覆盖同一个状态,因此提交时只会保留最后一次输入的内容。

修复方案

我们可以调整状态结构,把多组输入的内容存在数组中,同时支持动态增删输入对,提交时将所有非空的有效输入对批量存入属性列表即可。修复后的完整代码如下:

import React, { useState } from "react";
import { Button, Form, Grid, Icon } from "semantic-ui-react";

function Sample() {
  const [attributes, setAttributes] = useState([]);
  // 用数组存储多组输入,默认初始化1组输入
  const [inputGroups, setInputGroups] = useState([{ color: "", size: "" }]);

  // 处理单组输入的修改
  const handleInputChange = (index, field, value) => {
    const newGroups = [...inputGroups];
    newGroups[index][field] = value;
    setInputGroups(newGroups);
  };

  // 新增一组输入
  const addInputGroup = () => {
    setInputGroups([...inputGroups, { color: "", size: "" }]);
  };

  // 删除指定组输入
  const removeInputGroup = (index) => {
    const newGroups = inputGroups.filter((_, i) => i !== index);
    setInputGroups(newGroups);
  };

  const onSubmit = (e) => {
    e.preventDefault();
    // 过滤掉空的输入组,批量存入属性列表
    const validGroups = inputGroups.filter(item => item.color.trim() && item.size.trim());
    const newAttributes = validGroups.map((item, idx) => ({
      id: new Date().getTime() + attributes.length + idx,
      color: item.color,
      size: item.size
    }));
    setAttributes([...attributes, ...newAttributes]);
    // 重置输入为默认1组空输入
    setInputGroups([{ color: "", size: "" }]);
  };

  return (
    <>
      <Form onSubmit={onSubmit}>
        <h2>Create a Child Attributes:</h2>
        <Form.Field>
          <Grid columns={3}>
            {inputGroups.map((group, index) => (
              <Grid.Row key={index}>
                <Grid.Column>
                  <Form.Input
                    placeholder="Please Enter Color"
                    label="Color: "
                    value={group.color}
                    onChange={(event) => {
                      handleInputChange(index, "color", event.target.value);
                    }}
                  />
                </Grid.Column>
                <Grid.Column>
                  <Form.Input
                    placeholder="Please Enter Size"
                    label="Size: "
                    value={group.size}
                    onChange={(event) => {
                      handleInputChange(index, "size", event.target.value);
                    }}
                  />
                </Grid.Column>
                <Grid.Column verticalAlign="bottom">
                  {/* 至少保留1组输入,所以第一组不显示删除按钮 */}
                  {inputGroups.length > 1 && (
                    <Button 
                      type="button" 
                      color="red" 
                      icon 
                      onClick={() => removeInputGroup(index)}
                    >
                      <Icon name="trash" />
                    </Button>
                  )}
                </Grid.Column>
              </Grid.Row>
            ))}
          </Grid>
          <Button type="button" onClick={addInputGroup} style={{ margin: "10px 0" }}>
            新增输入组
          </Button>
          <br />
          <Button type="submit" color="teal">
            Submit
          </Button>
        </Form.Field>
      </Form>

      <table className="ui celled sortable table">
        <thead>
          <tr>
            <th>ID</th>
            <th>Color</th>
            <th>Size</th>
          </tr>
        </thead>
        <tbody>
          {attributes.map(({ id, color, size }) => (
            <tr key={id}>
              <td>{id}</td>
              <td>{color}</td>
              <td>{size}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </>
  );
}

export default Sample;

功能说明

  • 默认展示1组颜色+尺寸输入,点击「新增输入组」可以添加更多输入对,输入组右侧的删除按钮可以删除多余的输入项
  • 提交时会自动过滤掉颜色或尺寸为空的无效输入,一次性把所有有效数据存入属性列表
  • 支持任意数量的输入对,满足同分类下2个、3个甚至更多值的录入需求

React学习建议

  • 优先吃透React官方文档的基础概念,重点练习状态管理、组件通信、Hook相关内容
  • 多做小型项目练手,比如待办清单、表单系统、简单的后台管理页,逐步积累复杂状态处理的经验
  • 遇到问题可以先查看相关生态的官方文档,比如你使用的Semantic UI React的官方示例,多参考成熟的实现方案

内容的提问来源于stack exchange,提问作者Mohammad Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 14:36:03