javascript - 无法更改文本字段中映射数据的值
问题描述
我在对象内有数组格式的数据。
这是 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>
))}{" "}
</>
))}
</>
解决方案
创建一个使用外部和内部数组索引的 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>
))}{" "}
</>
))}
推荐阅读
- android - ADB install 命令的源代码在哪里?
- angular - 使用包含可观察到的检索令牌的拦截器设置授权标头
- javascript - 如何让用户使用使用 javascript 的按钮添加新字段?
- python - 在 Python 中从文本文件创建变量
- excel - 在 Powershell 生成的 Excel 文件中格式化图表 DataLabel
- python - Docker即使在杀死后也继续在后台运行进程
- mysql - 如何根据同一表中的字段在一个字段中插入和增加一个值
- flutter - MethodChannel、EventChannel 和 BasicMessageChannel 有什么区别?
- vba - 列表框 - 第一项保持选中状态
- python - WTForms 未将正确的数据类型保存到数据存储区