import React, { Component } from 'react'
export default class Shopcart extends Component {
constructor(props) {
super();
this.state = {
shopList: [
{ id: 0, goodName: '苹果', price: 20, num: 1 },
{ id: 1, goodName: '香蕉', price: 40, num: 5 },
{ id: 2, goodName: '橘子', price: 20, num: 6 },
{ id: 3, goodName: '榴莲', price: 50, num: 1 },
{ id: 4, goodName: '樱桃', price: 60, num: 11 }
]
}
}
//修改数据
changeNum(index, num) {
// console.log(index,num)
this.state.shopList[index].num += num;
this.setState({
shopList: this.state.shopList
})
}
//删除数据
delect = (index)=> {
//删除数据
this.state.shopList.splice(index,1)
this.setState({
shopList: this.state.shopList
})
}
render() {
return (
<div>
<h1>购物车的创建</h1>
<table>
<thead>
<tr>
<th>商品</th>
<th>单价</th>
<th>数量</th>
<th>合计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{
this.state.shopList.map((item, key) => {
return <tr key={item.id}>
<td>{item.goodName}</td>
<td>{item.price}</td>
<td>
<button onClick={this.changeNum.bind(this, key, -1)} disabled = {item.num < 2 ? 'disabled' : ''}>-</button>
{item.num}
<button onClick={this.changeNum.bind(this, key, 1)}>+</button>
</td>
<td>{item.price * item.num}</td>
<td>
<button onClick={()=> this.bind(key) }>删除</button>
</td>
</tr>
})
}
</tbody>
</table>
</div>
)
}
}