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

React中动态新增输入框行:如何在当前行下方插入而非数组末尾

实现方案

你需要改造addInputRow函数,让其接收当前行的索引作为入参,将新行插入到指定位置即可,以下是两种常用的不可变更新实现方式:

方式1:使用数组slice方法(更符合React不可变更新习惯)

const addInputRow = (currentIndex) => {
  setInfoValues([
    // 保留当前索引及之前的所有行
    ...infoValues.slice(0, currentIndex + 1),
    // 插入新行
    { name: "新用户", Age: 0, height: 0, weight: 0 },
    // 拼接当前索引之后的原有行
    ...infoValues.slice(currentIndex + 1)
  ]);
};

方式2:使用splice方法(写法和删除逻辑统一)

const addInputRow = (currentIndex) => {
  const valueList = [...infoValues];
  // splice参数:插入位置、删除元素数量、插入的新元素
  valueList.splice(currentIndex + 1, 0, { name: "新用户", Age: 0, height: 0, weight: 0 });
  setInfoValues(valueList);
};

渲染层绑定

在渲染每一行的新增按钮时,将当前行的索引传入方法即可:

{infoValues.map((item, index) => (
  <div key={index}>
    {/* 原有姓名、年龄、身高、体重输入框逻辑 */}
    <button onClick={() => addInputRow(index)}>下方插入行</button>
    <button onClick={() => removeInputRow(index)}>删除当前行</button>
  </div>
))}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:45:03