react简单购物车实现

发布博客的第一天,加油!

话不多说,上代码。

购物车

     

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>

        )

    }

}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值