简易购物车

效果图:

 

界面:

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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值