首页 > 解决方案 > 无法更改文本字段中映射数据的值

问题描述

我在对象内有数组格式的数据。

这是 JSON 数据:

[
  {
    "id": "1",
    "details": [
      { "id": "12wer1", "name": "ABC", "age": 15 },
      { "id": "78hbg5", "name": "FRE", "age": 21 }
    ]
  },
  {
    "id": "2",
    "details": [
      { "id": "po78u9", "name": "TER", "age": 18 },
      { "id": "dre87u", "name": "YUN", "age": 30 }
    ]
  }
]


我想分别更改“id”的名称和年龄。它不应该改变另一个“id”。例如:如果我想更改名称 =“ABC”,那么它不应该更改为名称 =“FRE”。但无法做到这一点。

任何人都可以帮助我为此编写正确的 onChange 函数并验证文本字段吗?

这是示例代码:

{this.state.Data.map((i) => (
          <>
            {i.details.map((y) => (
              <Grid container justify="center" spacing={2}>
                <Grid item xs={3}>
                  <TextField label="Name" variant="outlined" value={y.name} />
                </Grid>
                <Grid item xs={3}>
                  <TextField label="Age" variant="outlined" value={y.age} />
                </Grid>
              </Grid>
            ))}{" "}
          </>
        ))}
      </>

这是工作代码

标签: javascriptreactjs

解决方案


创建一个使用外部和内部数组索引的 onChange 处理程序,并onChange使用映射索引将旧状态映射到新状态以匹配您要更新的对象。

handleChange = (dataIndex, detailIndex) => (e) => {
  const { id, value } = e.target;
  this.setState(({ Data }) => ({
    Data: Data.map((dataItem, data_index) =>
      data_index === dataIndex
        ? {
            ...dataItem,
            details: dataItem.details.map((item, index) =>
              index === detailIndex
                ? {
                    ...item,
                    [id]: value
                  }
                : item
            )
          }
        : dataItem
    )
  }));
};

为输入提供id属性以传入事件对象。

{this.state.Data.map((i, dataIndex) => ( // <-- data index
  <>
    {i.details.map((y, detailIndex) => ( // <-- detail index
      <Grid container justify="center" spacing={2}>
        <Grid item xs={3}>
          <TextField
            label="Name"
            id="name" // <-- id name attribute
            variant="outlined"
            value={y.name}
            onChange={this.handleChange(dataIndex, detailIndex)} // <-- onChange callback
          />
        </Grid>
        <Grid item xs={3}>
          <TextField
            label="Age"
            id="age" // <-- id age attribute
            variant="outlined"
            value={y.age}
            onChange={this.handleChange(dataIndex, detailIndex)} // <-- onChange callback
          />
        </Grid>
      </Grid>
    ))}{" "}
  </>
))}

编辑无法更改映射数据在文本字段中的值


推荐阅读