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

React中如何更新嵌套对象数组中对应文本输入框的值

解决方案

你只需要在触发更新函数时额外传递当前输入框对应的记录索引和值索引,就可以复用同一个更新函数处理所有输入框的修改,不需要单独为每个输入框编写处理逻辑,具体修改如下:

1. 修改子组件 Content.jsx

给每个输入框的onChange回调传入对应的记录下标和值下标,示例代码:

export default function Content({ updateDoc, ...formDocument }) {
  const records = formDocument.document.content.records;
  return (
    <div>
      <input
        style={{ display: "block", marginTop: "10px" }}
        type="text"
        value={records[0].values[0]}
        onChange={(e) => updateDoc(e, 0, 0)}
      />
      <input
        style={{ display: "block", marginTop: "10px" }}
        type="text"
        value={records[0].values[1]}
        onChange={(e) => updateDoc(e, 0, 1)}
      />
    </div>
  );
}

如果后续你是通过遍历fields数组批量渲染输入框,直接用遍历的下标作为值索引即可,不需要手动硬编码每个下标。

2. 修改父组件的 updateDocument 方法

接收传递过来的索引参数,按照React state不可变更新的原则修改对应位置的值即可:

const updateDocument = (e, recordIndex, valueIndex) => {
  const inputValue = e.target.value;
  setFormDocument(prev => {
    // 逐层拷贝避免直接修改原state
    return {
      ...prev,
      document: {
        ...prev.document,
        content: {
          ...prev.document.content,
          records: prev.document.content.records.map((record, idx) => {
            if (idx !== recordIndex) return record;
            return {
              ...record,
              values: record.values.map((val, vIdx) => 
                vIdx === valueIndex ? inputValue : val
              )
            }
          })
        }
      }
    }
  });
};

如果你的运行环境支持structuredCloneAPI,也可以用深拷贝简化写法:

const updateDocument = (e, recordIndex, valueIndex) => {
  const inputValue = e.target.value;
  setFormDocument(prev => {
    const newDoc = structuredClone(prev);
    newDoc.document.content.records[recordIndex].values[valueIndex] = inputValue;
    return newDoc;
  });
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:57:00