import React, { Component } from 'react'; import { Checkbox, WhiteSpace } from 'antd-mobile'; import classNames from 'classnames'; import './index.css' class CartItem extends Component { constructor(props){ super(props); this.state={ cartList:[], totalPrice:0, isSelectAll:true, selectedCount:0 }; } //获取数据 componentWillMount(){ const cartList = [ {id:'1',name:'test1',count:1,img:'',price:10}, {id:'2',name:'test2',count:2,img:'',price:20} ]; this.setState({ cartList },()=>{ this.checkedAll('',true); }); } //获取输入框的值 getInputValue=(e,i)=>{ this.setState({ cartList:this.state.cartList.map((ele,index)=>{ if(index===i){ ele.count=e.target.value; return ele }else { return ele } }) }); this.sumPrice(); }; // 增加 augment=(e,i)=>{ this.setState({ cartList:this.state.cartList.map((ele,index)=>{ if(index===i){ ele.count=ele.count*1+1; return ele }else { return ele } }) }); this.sumPrice() }; // 减少 reduce=(e,i)=> { this.setState({ cartList:this.state.cartList.map((ele,index)=>{ if(index===i){ ele.count=ele.count*1-1; return ele }else { return ele } }) }); this.sumPrice(); }; //删除 del=(e,i)=> { this.setState({ cartList:this.state.cartList.filter((ele,index)=>{ if(index!==i){ return true }else { return false } }) }); setTimeout(()=>{ this.sumPrice() },1) }; // 改变选择 changeCheckedStatus=(e,i)=>{ this.setState({ cartList:this.state.cartList.map((ele,index)=>{ if(index===i){ ele.checked=!ele.checked } return ele }) }); this.sumPrice(); }; //全选或全不选,判断全选状态 checkedAll=(e,check)=>{ let checked = e.target ? e.target.checked : check; if(checked===true){ this.setState({ cartList:this.state.cartList.map((ele,index)=>{ ele.checked=true; return ele }), isSelectAll:true }); }else if(checked===false){ this.setState({ cartList:this.state.cartList.map((ele,index)=>{ ele.checked=false; return ele }), isSelectAll:false }); } this.sumPrice(); }; //计算总合计 sumPrice=()=>{ let totalPrice=0,selectedCount=0; this.state.cartList.forEach((ele,index)=>{ if(ele.checked===true){ totalPrice+=ele.count*ele.price; selectedCount+=ele.count; } }); this.setState({ totalPrice, selectedCount }); }; //结算传值 settleAccounts=()=>{ let shopping=[]; this.state.cartList.forEach((ele,index)=>{ if(ele.checked===true){ shopping.push(ele) } }); console.log('shopping',shopping); window.localStorage.setItem("shopping",JSON.stringify(shopping)); window.localStorage.setItem("sumprice",JSON.stringify(this.state.totalPrice)); this.props.history.push('/jiesuan') }; render() { return (
{ this.state.cartList.map((ele,index)=>{ return(
{this.changeCheckedStatus(e,index)}} />
{ele.name}
颜色尺码等
¥ {ele.price}
{this.getInputValue(e,index)}}/>
) }) }
{this.checkedAll(e,'')}} style={{marginLeft:15}} />, 全选
合计: ¥ {this.state.totalPrice}
); } } export default CartItem;