【发布时间】:2019-09-21 14:39:34
【问题描述】:
我有 myrecords[] 状态,其中包含以下格式的 JSON 对象:
{
"records": {
"Master Automotives": [
{
"SparePartID": "43",
"Name": "Oil and Lubricants",
"Price": "4500",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "4500"
},
{
"SparePartID": "45",
"Name": "Lights",
"Price": "2300",
"VendorID": "48",
"CompanyName": "Master Automotives",
"Qty": 1,
"TotalPrice": "2300"
}
],
"Repair Solutions": [
{
"SparePartID": "47",
"Name": "Steering Wheel",
"Price": "1500",
"VendorID": "60",
"CompanyName": "Repair Solutions",
"Qty": 1,
"TotalPrice": "1500"
}
],
"FiveStar Automotives": [
{
"SparePartID": "51",
"Name": "Brakes",
"Price": "234",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "234"
},
{
"SparePartID": "53",
"Name": "Clutch",
"Price": "999",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "999"
},
{
"SparePartID": "55",
"Name": "LED",
"Price": "288",
"VendorID": "70",
"CompanyName": "FiveStar Automotives",
"Qty": 1,
"TotalPrice": "288"
}
]
}
}
现在我在 react js 中显示这条记录,所有项目都显示在行中并按它们的 CompanyNames 分组,并且每个项目都有一个数量的输入字段。 默认数量为 1,因此 TotalPrice 与 UnitPrice 相同。
现在我想要 Qty 的任何特定输入字段的 onChange,JSON Object 中相应的 TotalPrice 项也应该在myrecords[] 状态。此外,Qty 也应该在 myrecords[] 状态下更新。
P.S:myrecords[] 包含 JSON object 而不是数组。
这是我的显示 JSON 对象记录的反应代码:
{Object.keys(this.state.myrecords).map((CompanyName, i) => (
<div key={CompanyName}>
<h2>Supplier: {CompanyName}</h2>
{this.state.myrecords[CompanyName].map((product, i) => (
<tr>
<td>
<h4> {product["SparePartID"]} </h4>
</td>
<td>
<h4>{product["Name"]} </h4>
</td>
<td>
<h4> {product["Price"]} </h4>
</td>
<td>
<input type="number"
value={product["Qty"]}
min="1"
onChange={(e) => this.onChangeQty(product["SparePartID"], e)}/>
</td>
<td> $ {product["TotalPrice"]}
</td>
</tr>
))}
</div>
))}
而onChangeQty函数如下**(这里是我需要帮助的地方)**:
onChangeQty(sid,e)
{
const items = this.state.myrecords;
const item = items.find(item => item.SparePartID === sid);
item.Qty = e.target.value;
item.TotalPrice = item.Qty * item.Price;
this.setState({
myrecords: items
});
}
【问题讨论】:
标签: javascript json reactjs state onchange