第8节——实战购物车功能

1、样例

第8节——实战购物车功能_第1张图片

2、需求

  • 单选全选功能,并且可以互相联动
  • 小计功能
  • 总计功能
  • 商品加减,数量为零时不能在减

3、代码

goods-item.jsx

import React from "react";

export default class GoodsItem extends React.Component {
    singleChange() {
        //调用父组件传过来的方法
        this.props.singleChange()
    }

    updateNum(actionType) {
        this.props.updateNum(actionType)
    }

    render() {
        const { item } = this.props
        // console.log(item)
        return (
            
this.singleChange()} /> 商品名:{item.name}---商品价格:{item.price}--- {item.num || 1} 小计:{item.price * (item.num || 1)}
) } }

shop-cart.jsx.jsx

import React from "react";
import GoodsItem from './goods-item'

export default class ShopCart extends React.Component {

    state = {
        goods: [
            {
                name: '羊肉串',
                price: 18,
            },
            {
                name: '鸡肉串',
                price: 20,
            },
            {
                name: '鸡翅',
                price: 5,
            },
        ],
        isAllSelect: false,
    }
    /* 
    数值操作
    index 当前下标
    actionType + || -
    */
    updateNum(index, actionType) {
        //num 进行初始化操作
        this.state.goods[index].num = this.state.goods[index].num || 1;

        //对数值进行操作
        this.state.goods[index].num += actionType;

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

    /* 
    全选方法
    */
    allSelectChange() {
        //修改全选方法
        this.state.isAllSelect = !this.state.isAllSelect;
        //把单选状态和全选状态一致
        this.state.goods.forEach((item) => {
            item.select = this.state.isAllSelect;
        });

        this.setState({
            isAllSelect: this.state.isAllSelect,
            goods: this.state.goods,
        })
    }

    singleChange(index) {
        //修改单选状态
        this.state.goods[index].select = !this.state.goods[index].select;

        //同步全选状态
        const isAllSelect = this.state.goods.every((item) => item.select);

        this.setState({
            isAllSelect,
            goods: this.state.goods,
        })
    }

    render() {
        return (
            

我是购物车

全选 this.allSelectChange()} />
{this.state.goods.map((item, index) => ( this.singleChange(index)} updateNum={(actionType) => this.updateNum(index, actionType)}> )) }
总计 : {this.state.goods.filter((item) => item.select).reduce((total, item) => (total += item.price * (item.num || 1)), 0)}
) } }

ds.filter((item) => item.select).reduce((total, item) => (total += item.price * (item.num || 1)), 0)}

)
}
}


你可能感兴趣的:(react,javascript,前端,react.js)