react實現購物車的數據

import React, { Component } from 'react'


export default class Shopcart extends Component {
    constructor(props) {
        super();

        this.state = {
            shopList: [
                { id: 0, goodName: '蘋果', price: 20, num: 1 },
                { id: 1, goodName: '香蕉', price: 40, num: 5 },
                { id: 2, goodName: '橘子', price: 20, num: 6 },
                { id: 3, goodName: '榴蓮', price: 50, num: 1 },
                { id: 4, goodName: '櫻桃', price: 60, num: 11 }
            ]
        }
    }
    //修改數據
    changeNum(index, num) {
        // console.log(index,num)
        this.state.shopList[index].num += num;

        this.setState({
            shopList: this.state.shopList
        })

    }

    //刪除數據
    delect = (index)=> {
        //刪除數據
        this.state.shopList.splice(index,1)

        this.setState({
            shopList: this.state.shopList
        })

    }
    render() {
        return (
            <div>
                <h1>購物車的創建</h1>
                <table>
                    <thead>
                        <tr>
                            <th>商品</th>
                            <th>單價</th>
                            <th>數量</th>
                            <th>合計</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.state.shopList.map((item, key) => {
                                return <tr key={item.id}>
                                    <td>{item.goodName}</td>
                                    <td>{item.price}</td>
                                    <td>
                                        <button onClick={this.changeNum.bind(this, key, -1)} disabled = {item.num < 2 ? 'disabled' : ''}>-</button>
                                        {item.num}
                                        <button onClick={this.changeNum.bind(this, key, 1)}>+</button>
                                    </td>
                                    <td>{item.price * item.num}</td>
                                    <td>
                                        <button onClick={()=> this.bind(key) }>刪除</button>
                                    </td>
                                </tr>
                            })
                        }

                    </tbody>
                </table>
            </div>
        )
    }
}

 

發佈了55 篇原創文章 · 獲贊 12 · 訪問量 4240
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章