zoukankan      html  css  js  c++  java
  • react做购物车的功能

    父组件

    import React, { Component } from 'react'
    import Lists from '../components/Lists'
    
    export default class Cart extends Component {
    
      // 数据 状态
      state = {
        carts: [
          { id: 1, name: '苹果11', price: 10, num: 1 },
          { id: 2, name: '小米10', price: 20, num: 1 },
          { id: 3, name: '华为meta40', price: 30, num: 1 }
        ]
      }
    
    
      render() {
        return (
          <div>
            {/* 功能组件 */}
            <Lists carts={this.state.carts} handlerCartNum={this.handlerCartNum.bind(this)} />
          </div>
        )
      }
    
      handlerCartNum(index, flag = 'incr') {
        let carts = this.state.carts
    
        if ('incr' === flag) {
          carts[index].num++
          /* this.setState({
            carts
          }) */
          /* this.setState(state=>{
            return {
              carts
            }
          }) */
        } else {
          // splice删数组中的数据影响原数组
          carts.splice(index, 1)
        }
        
        this.setState(state => ({ carts }))
      }
    }

    子组件

    import React, { Component } from 'react'
    import '../styles/lists.css'
    
    import PropTypes from 'prop-types'
    
    export default class Lists extends Component {
    
      static propTypes = {
        carts: PropTypes.arrayOf(PropTypes.shape({
          id: PropTypes.number,
          name: PropTypes.string,
          num:PropTypes.number
        }))
      }
    
    
      render() {
        let { carts } = this.props
        return (
          <ul>
            {
              carts.map((item, index) => (
                <li key={item.id}>
                  <span>ID:{item.id}</span>
                  <span>名称:{item.name}</span>
                  <span>价格:{item.price}</span>
                  <span>数量:
                  <button onClick={this.incr.bind(this, index)}>+</button>
                    {/* <button onClick={() => this.incr(index)}>+</button> */}
                    {item.num}
                    <button onClick={this.decr.bind(this, index)}>-</button>
                  </span>
                  <span>小计:{item.num * item.price}</span>
                </li>
              ))
            }
          </ul>
        )
      }
    
      incr(index) {
        // 调用父级中的props传入的函数方法
        this.props.handlerCartNum(index)
      }
    
      decr(index) {
        // 调用父级中的props传入的函数方法
        this.props.handlerCartNum(index, 'decr')
      }
    
    
    }
    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    POJ2965(The Pilots Brothers' refrigerator)
    POJ1753(Flip Game)
    POJ3253(Fence Repair)
    山东理工大学的训练计划
    loutsScript 常用代码
    《大道至简》读后感
    2019暑第三周
    2019暑第二周
    2019暑第一周
    关于13组作品《TD tree》的使用感想
  • 原文地址:https://www.cnblogs.com/ht955/p/14668044.html
Copyright © 2011-2022 走看看