效果图:
界面:
import React, { Component } from 'react';//引入react
import './Css.css';//引入css
export default class Cart extends Component {
constructor(props) {
super(props)
this.state = {
list: [//数据
{ id: 1, title: '提子', price: 150, count: 1 },
{ id: 2, title: '碧根果', price: 50, count: 1 },
{ id: 3, title: '椰子', price: 100, count: 1 },
{ id: 4, title: '鲜苹果', price: 90, count: 1 },
{ id: 5, title: '香蕉', price: 160, count: 1 }
]
}
}
// 删除功能
handleDelete(id) {
this.setState({
list: this.state.list.filter(o => o.id !== id)
})
}
// 增加减少按钮
handleClick(id, num) {
let res = []
this.state.list.forEach(o => {
if (id === o.id) { // 找到数据了
o.count += num
}
res.push(o)
})
this.setState({
list: res
})
}
// 计算总价
getTotal() {
let total = 0
this.state.list.forEach(o => {
total += o.price * o.count
})
return total.toFixed(2)
}
render() {
const { list } = this.state
return (
<div className='div'>
<table>
<thead>
<tr>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{
list.map(o => <tr key={o.id}>
<td>{o.title}</td>
<td>¥{o.price}/斤</td>
<td className='num'>
<button className='button' disabled={o.count === 1} onClick={() => this.handleClick(o.id, -1)}>-</button>
<span>{o.count}</span>
<button className='button' onClick={() => this.handleClick(o.id, 1)}>+</button>
</td>
<td>{(o.price * o.count)}元</td>
<td><button onClick={() => this.handleDelete(o.id)}>删除</button></td>
</tr>
)
}
</tbody>
</table>
<div className='getTotal'>总价: {this.getTotal()}元</div>
</div>
)
}
}
样式:
.div{
text-align: center;
display: flex;
flex-direction: column;
}
thead{
background-color: brown;
}
tbody{
background-color: rgb(156, 45, 5);
}
button{
background-color: rgb(225, 125, 18);
cursor: pointer;
}
.button{
font-size: 20px;
color: black;
}
.num{
display: flex;
flex-direction: row;
justify-content: space-around;
}
.getTotal{
background-color: red;
font-size: 20px;
}