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

React实现动态输入框并存储对应输入内容的问题咨询

解决方案:实现输入文本存入生成的字段

问题分析

你的代码核心问题在于:

  • 所有生成的输入框共享同一个input状态,导致内容完全同步,无法单独维护每个字段的文本
  • count数组仅存储无意义的{count:0}对象,没有保存每个输入项的实际内容
  • 多余的length、num、myHashMap状态不仅没用,还增加了逻辑复杂度(组件每次渲染都会重新创建myHashMap,根本无法持久化数据)

修改后的完整代码

import React, { useState } from "react";

const Add = () => {
  // 存储当前输入框的临时文本
  const [inputValue, setInputValue] = useState("");
  // 存储所有生成的输入项文本,数组元素对应每个输入框的内容
  const [items, setItems] = useState([]);

  // 处理回车事件:添加新输入项
  const handleKeyPress = (event) => {
    if (event.charCode === 13 && inputValue.trim()) {
      // 将当前输入文本添加到items数组,同时清空输入框
      setItems(prevItems => [...prevItems, inputValue.trim()]);
      setInputValue("");
    }
  };

  // 修改指定索引的输入项内容
  const handleItemChange = (index, newValue) => {
    setItems(prevItems => {
      const updatedItems = [...prevItems];
      updatedItems[index] = newValue;
      return updatedItems;
    });
  };

  // 删除指定索引的输入项
  const handleItemRemove = (index) => {
    setItems(prevItems => prevItems.filter((_, i) => i !== index));
  };

  return (
    <div>
      <input
        type="text"
        id="bar"
        className="form-control"
        onKeyPress={handleKeyPress}
        onChange={(e) => setInputValue(e.target.value)}
        placeholder="Add New "
        value={inputValue}
      />
      {items.map((itemText, index) => (
        <div key={index} className="input-group mb-3 mt-2">
          <div className="input-group-text">
            <input className="form-check-input mt-0" type="checkbox" />
          </div>
          <input
            type="text"
            className="form-control"
            value={itemText}
            onChange={(e) => handleItemChange(index, e.target.value)}
          />
          <button 
            className="btn btn-outline-danger"
            onClick={() => handleItemRemove(index)}
          >
            X
          </button>
        </div>
      ))}
    </div>
  );
};

export default Add;

关键修改点说明

  1. 状态重构

    • 用inputValue存储主输入框的临时文本,items数组存储所有生成的输入项内容,每个元素对应一个输入框的文本
    • 移除了所有无意义的冗余状态(length、num、myHashMap)
  2. 回车逻辑优化

    • 按下回车时,先判断输入内容非空,再将文本添加到items数组,同时清空主输入框
    • 使用函数式更新setItems(prevItems => ...)确保获取最新的数组状态
  3. 独立维护每个输入项

    • 每个生成的输入框绑定对应索引的itemText作为value
    • 通过handleItemChange函数单独更新指定索引的输入项内容
    • 完善了删除功能,点击按钮即可移除对应输入项
  4. 细节修复

    • 主输入框添加了value={inputValue}实现受控组件,确保状态和视图同步
    • 修复了按钮的class拼写错误(应为className,符合React规范)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 10:26:24