发布博客的第一天,加油!
话不多说,上代码。
购物车
import React, { Component } from 'react'
export default class Cart extends Component {
constructor(props) {
super(props)
this.state = {
list: [
{id:1,title:'提子',price:50,count:1},
{id:2,title:'碧根果',price:50,count:1},
{id:3,title:'牛奶',price:50,count:1},
{id:4,title:'牛肉',price:50,count:1}
]
}
}
// 删除功能
handleDelete(id) {
this.setState({
list: this.state.list.filter(v => v.id !== id)
})
}
// 增加减少按钮
handleClick(id, num) {
let res = []
this.state.list.forEach(v => {
if(id === v.id) { // 找到数据了
v.count += num
}
res.push(v)
})
this.setState({
list: res
})
}
// 计算总价
getTotal() {
let total = 0
this.state.list.forEach(v => {
total += v.price * v.count
})
return total.toFixed(2)
}
render() {
const { list } = this.state
return (
<div>
<table>
<thead>
<tr>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{
list.map(v => <tr key={v.id}>
<td>{v.title}</td>
<td>{v.price}</td>
<td>
//减 disabled={ v.count === 1 } 不能加到负数
<button disabled={ v.count === 1 } onClick={ () =>
this.handleClick(v.id, -1) }>-</button>
<span>{v.count}</span>
//加
<button onClick={ () => this.handleClick(v.id, 1) }>+</button>
</td>
<td>{ (v.price * v.count)</td>
//删除
<td><button onClick={() => this.handleDelete(v.id)}>删除</button></td>
</tr>
)}
</tbody>
</table>
总价: { this.getTotal() }
</div>
)
}
}