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

React中使用map生成多输入框的子项同步问题求助

问题根源与解决方案

你当前的核心问题是所有输入组共享了同一个lotsState全局状态,导致新增输入组时会自动渲染所有已存在的子输入项。要实现每个输入组独立管理自身子项,需要重构状态结构,让每个输入组拥有专属的子项状态。


1. 重构状态结构

将原来的itemState从单纯的数字数组,改为包含每个输入组专属lots子项数组的对象数组,确保子项状态完全独立:

const [itemState, setItemState] = useState([{ id: 0, lots: [0] }]);

用id标识输入组,比直接用索引更稳妥,避免列表变动时的key冲突问题。

2. 修改新增输入组的方法

新增输入组时,默认给它初始化一个仅含一行子项的lots数组:

const addItemCount = useCallback(() => {
  const lastId = itemState[itemState.length - 1].id;
  setItemState(prev => [...prev, { id: lastId + 1, lots: [0] }]);
}, [itemState]);

采用函数式更新状态,符合React状态更新的最佳实践。

3. 修改新增子项的方法

现在需要给指定输入组新增子项,所以要接收输入组的索引,定位到对应项后更新其lots数组:

const addLotsCount = useCallback((itemIndex) => {
  setItemState(prev => {
    const newItems = [...prev];
    const targetItem = newItems[itemIndex];
    // 给当前输入组的子项数组新增元素
    targetItem.lots = [...targetItem.lots, targetItem.lots.length];
    return newItems;
  });
}, []);

通过函数式更新直接依赖前状态,无需在依赖数组中加入itemState,减少不必要的重渲染。

4. 调整渲染逻辑

每个输入组循环自身的item.lots数组,同时修正key值(避免子项key重复):

{itemState.map((item, index2) => {
  return (
    <div id={`single-${item.id}`} key={item.id}>
      <div
        className="material-symbols-outlined"
        style={{ fontVariationSettings: "'FILL' 1" }}
        onClick={addItemCount}
      >
        add_box
      </div>
      <Form.Group className="mb-3 name">
        <Form.Label>Name</Form.Label>
        <Form.Control type="text" />
      </Form.Group>
      <div className="lots-quantity">
        {item.lots.map((lot, index3) => {
          return (
            <div className="lots" key={index3}>
              <Form.Group className="mb-3 selection">
                <Form.Label>items</Form.Label>
                <Form.Select aria-label="Default select example">
                  <option>Open this select menu</option>
                  <option value="1">One</option>
                  <option value="2">Two</option>
                  <option value="3">Three</option>
                </Form.Select>
              </Form.Group>
              <Form.Group className="mb-3 quantity">
                <Form.Label>quantity</Form.Label>
                <Form.Control type="text" />
              </Form.Group>
              <div
                className="material-symbols-outlined"
                style={{ fontVariationSettings: "'FILL' 1" }}
                onClick={() => addLotsCount(index2)}
              >
                add_box
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
})}

关键调整点:

  • 输入组的key用item.id,避免索引变动导致的组件异常
  • 子项的key用自身索引index3,确保每个子项key唯一
  • 点击子项添加按钮时,传递当前输入组的index2,明确指定要新增子项的目标组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 19:07:02