- App.js
```javascript
import React, { Component } from ‘react’;
import ‘./App.css’;
import { Checkbox, InputNumber, Button } from ‘antd’;
class Carts extends Component {
constructor(props) {
super(props);
this.state = {
products: [],checkedAll:true
}
}
render() {
return (<div className="center container"> <h2>购物车</h2> <table className="table table-hover"> <thead> <tr> <th>全选<Checkbox onChange={this.onCheckAll} checked={this.state.checkedAll}></Checkbox></th> <th>商品</th> <th>单价</th> <th>数量</th> <th>小计</th> <th>操作</th> </tr> </thead> <tbody> {this.state.products.map(item => { return (<tr key={item.id}> <td> <Checkbox onChange={this.onCheck.bind(this,item.id)} checked={item.isSelected}></Checkbox> </td> <td className="produce"> <img src={item.productCover} /> <p className="title">{item.productName}</p> </td> <td> <div className="price">{item.productPrice}</div> </td> <td> <InputNumber size="small" min={1} defaultValue={item.productCount} onChange={this.onChange.bind(this, item.id)} /> </td> <td> <div>${this.Subtotal(item.productPrice, item.productCount)}</div> </td> <td> <Button className="btn" onClick={this.handleDel.bind(this,item)}>删除</Button> </td> </tr>) })} </tbody> </table> <p>总价: {this.sum()}</p></div>
);
}
componentDidMount() {
this.axios.get(‘http://yapi.demo.qunar.com/mock/34830/carts').then(res => {this.setState({ products: res.data})
})
}
onChange(id, e) {
var products = this.state.products
products.forEach(item => {if (item.id == id) { item.productCount = e}
})
this.setState({products
})
}
handleDel(item){
var products = this.state.products.filter(value=>value!==item)
this.setState({products:products
})
}
onCheck(id,e){
var products = this.state.products
products.forEach(item=>{if(item.id==id){ item.isSelected = e.target.checked}
})
this.setState({products
})
this.get()
}
onCheckAll=(e)=>{
var checkedAll = this.state.checkedAll
this.setState({checkedAll:!checkedAll
})
this.set(e.target.checked)
}
get(){
var products = this.state.products
var checkedAll = products.every(item=>item.isSelected)
this.setState({checkedAll
})
}
set(val){
var products = this.state.products
products.forEach(item=>item.isSelected = val)
this.setState({products
})
}
Subtotal(a, b) {
return (a * b).toFixed(2)
}
sum() {
var products = this.state.products
var total = 0;
for (let i = 0; i < products.length; i++) {if (products[i].isSelected) { total = total + products[i].productCount * products[i].productPrice;} else { continue;}
}
return total.toFixed(2)
}
}
export default Carts;
- App.css```javascript.center{ margin: 20px auto; text-align: center;}.container{ width: 850px;}img{ width: 100px;height: 150px;}th,td{ padding: 0 30px; }table{ border: 1px solid#eee;}.price{ width: 100px; border: 1px solid #eee;}.btn{ background: crimson; color: white; border: none; font-size: 14px;}