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

React实现根据输入数字动态添加对应数量输入框的问题

React 按输入数量批量添加动态输入框

实现步骤:

  1. 新增状态存储输入数量:添加一个状态变量,专门保存用户输入的要添加的输入框数量。
  2. 添加数字输入区域:做一个输入框供用户输入数字,同时处理输入内容,只保留有效数字。
  3. 修改批量添加逻辑:点击按钮时,根据输入的数字生成对应数量的空表单对象,追加到原有表单数据中。
  4. 边界情况处理:过滤负数、0和非数字的无效输入,避免异常。

完整代码示例:

import { useState } from 'react';

function DynamicForm() {
  // 原有的表单数据状态
  const [formValues, setFormValues] = useState([{ name: "", email: "" }]);
  // 新增:存储用户输入的要添加的数量
  const [inputCount, setInputCount] = useState("");

  // 处理动态输入框的内容变更
  const handleChange = (index, e) => {
    const { name, value } = e.target;
    const updatedValues = [...formValues];
    updatedValues[index][name] = value;
    setFormValues(updatedValues);
  };

  // 处理数量输入框的变更,只保留数字字符
  const handleCountChange = (e) => {
    const numValue = e.target.value.replace(/[^0-9]/g, "");
    setInputCount(numValue);
  };

  // 批量添加输入框的核心逻辑
  const addBatchFormFields = () => {
    const count = parseInt(inputCount, 10);
    // 仅当输入是正整数时执行添加
    if (count > 0) {
      // 生成对应数量的空表单对象
      const newFields = Array(count).fill({ name: "", email: "" });
      // 追加到现有表单数据中
      setFormValues([...formValues, ...newFields]);
      // 清空数量输入框
      setInputCount("");
    }
  };

  return (
    <div>
      {/* 数量输入控制区 */}
      <div style={{ marginBottom: "15px" }}>
        <label>要添加的输入框数量:</label>
        <input
          type="text"
          value={inputCount}
          onChange={handleCountChange}
          placeholder="请输入数字"
          style={{ margin: "0 10px" }}
        />
        <button
          className="button add"
          type="button"
          onClick={addBatchFormFields}
        >
          批量添加
        </button>
      </div>

      {/* 渲染动态生成的输入框 */}
      {formValues.map((element, index) => (
        <div key={index} style={{ margin: "10px 0" }}>
          <span>Name:</span>
          <input
            type="text"
            name="name"
            value={element.name || ""}
            onChange={(e) => handleChange(index, e)}
            style={{ margin: "0 5px" }}
          />
          <span>Email:</span>
          <input
            type="text"
            name="email"
            value={element.email || ""}
            onChange={(e) => handleChange(index, e)}
            style={{ margin: "0 5px" }}
          />
        </div>
      ))}
    </div>
  );
}

export default DynamicForm;

关键细节说明:

  • 输入过滤:用正则replace(/[^0-9]/g, "")过滤非数字字符,确保用户只能输入有效数字。
  • 批量生成:通过Array(count).fill()快速创建指定数量的空表单对象,再用扩展运算符合并到原数组,符合React状态不可变的要求。
  • 有效性校验:判断count为正整数才执行添加操作,避免无效输入导致的逻辑异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:10:36