import React from 'react';
import axios from "axios"
export default class Shou extends React.Component{
constructor(props){
super(props)
this.state={
shopList:[],
sum:0,
allCheck:false
}
}
componentDidMount(){
// axios get请求数据
axios.get("https://easy-mock.com/mock/5cef725e8394f43f3cf2a566/shop/shopcart").then(res=>{
console.log(res.data)
if(res.data.code==200){
// 添加checked 属性
let data=res.data.data.shop;
for(var i=0;i<data.length;i++){
// 默认fasle
data[i].checked=false;
}
console.log(data)
this.setState({
shopList:data
})
this.getSum()
}
})
}
//加加
add(index){
let shopList=this.state.shopList;
shopList[index].count++;
this.setState({shopList:shopList})
this.getSum()
}
//减减
reduce(index){
let shopList=this.state.shopList;
shopList[index].count--;
if(shopList[index].count<1){
alert("数量不能为0")
shopList[index].count=1;
}else{
this.setState({shopList:shopList})
}
this.getSum()
}
//单个复选框
change(index){
let shopList=this.state.shopList;
shopList[index].checked=!shopList[index].checked;
var allcheck=shopList.every((item,index)=>{
return item.checked==true;
})
this.setState({shopList:shopList,allCheck:allcheck})
this.getSum()
}
//计算 小计
getSum(){
let sum=0;
let data=this.state.shopList;
for(let i=0;i<data.length;i++){
if(data[i].checked==true){
sum+=data[i].price*data[i].count
}
}
this.setState({sum:sum})
}
// 点击全选复选框
allcheck(){
let check=!this.state.allCheck;
console.log(check)
let data=this.state.shopList;
for(let i=0;i<data.length;i++){
data[i].checked=check;
}
this.setState({shopList:data,allCheck:check})
this.getSum()
}
//删除按钮
delete(index){
let data=this.state.shopList;
data.splice(index,1)
this.setState({shopList:data})
this.getSum()
}
render(){
return(
<div className="cart">
<h4>购物车</h4>
{
this.state.shopList.map((item,index)=>{
return(
<div key={index} className="shopList">
<div className="cartcheck">
<input type="checkbox" onClick={this.change.bind(this,index)} checked={item.checked} />
</div>
<div className="cartimg">
<img src={item.imgurl} />
</div>
<div className="cartname">
<p>{item.name}</p>
</div>
<div className="cartkuang">
<button onClick={this.reduce.bind(this,index)}>-</button>
<input disabled type="text" value={item.count} />
<button onClick={this.add.bind(this,index)}>+</button>
</div>
<div className="cartprice">
<p> 总价{item.price*item.count}</p>
<button onClick={this.delete.bind(this,index)}>删除</button>
</div>
</div>
)
})
}
<div>
<input type="checkbox" checked={this.state.allCheck}
onClick={this.allcheck.bind(this)} />
<button>全选</button>
总价 {this.state.sum}
</div>
</div>
)
}
}
react 购物车
最新推荐文章于 2023-08-24 20:41:21 发布