```javascript
import React from "react";
class Car extends React.Component {
constructor() {
super();
this.state = {
arr: [
{ id: 1, name: "商品1", price: 1, num: 1 },
{ id: 2, name: "商品2", price: 2, num: 1 },
{ id: 3, name: "商品3", price: 3, num: 1 },
{ id: 4, name: "商品4", price: 4, num: 1 },
{ id: 5, name: "商品5", price: 5, num: 1 },
],
}
}
changeNumber(id, num) {
// for (const obj of this.state.arr) {
// console.log(obj);
// }
this.state.arr.forEach((obj) => {
if (id == obj.id) {
obj.num += num
}
})
this.setState({
arr: this.state.arr
})
}
delatarr(id) {
for (const obj of this.state.arr) {
if (id == obj.id) {
let index = this.state.arr.indexOf(obj);
this.state.arr.splice(index, 1)
}
}
this.setState({
arr: this.state.arr,
})
}
pushgoods() {
var length = this.state.arr.length;
this.setState({
arr: [...this.state.arr, { id: length + 1, name: "商品" + (length + 1), price: 5, num: 1 }]
})
}
render() {
let tbody = this.state.arr.map((obj) => {
return <tr key={obj.id}>
<td>{obj.id}</td>
<td>{obj.name}</td>
<td>{obj.price}</td>
<td>{obj.num}</td>
<td>{obj.num * obj.price}</td>
<td>
<button disabled={obj.num == 1} onClick={this.changeNumber.bind(this, obj.id, -1)}>-</button>
<span>{obj.num}</span>
<button onClick={this.changeNumber.bind(this, obj.id, +1)}>+</button>
</td>
<td><button onClick={this.delatarr.bind(this, obj.id)}>删除</button></td>
</tr>
})
return (
<div>
<table border="1" width="500">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>price</th>
<th>num</th>
<th>小计</th>
<th>操作</th>
<th>shanchu</th>
</tr>
</thead>
<tbody>
{tbody}
</tbody>
</table>
<h1>总价:{
this.totalprice()
}</h1>
<button onClick={this.pushgoods.bind(this)}>添加一个商品</button>
</div>
)
}
totalprice() {
var totalprice = 0;
this.state.arr.map((obj) => {
totalprice += obj.num * obj.price
})
return totalprice;
}
}
export default Car;