React 中购物车功能实现(实现总价的动态生成)
2022-07-30 本文已影响0人
一只程序元
样式代码:
import React, { Component } from 'react'
import "./Page.css"
export default class Page extends Component {
state = {
arr: [
{ id: 1, goodName: '杨枝甘露', goodPrice: 20, num: 1 },
{ id: 2, goodName: '森林玫果', goodPrice: 30, num: 1 },
{ id: 3, goodName: '烤奶', goodPrice: 15, num: 1 }
],
allChecked: false,
totalPrice: 0
}
checkNum = 0
itemChange = (event, e) => {
const checked = event.target.checked;
const { arr } = this.state;
e.checked = checked;
if (checked) {
this.checkNum++;
} else {
this.checkNum--;
}
if (this.checkNum === arr.length) {
this.setState({
allChecked: true
})
} else {
this.setState({
allChecked: false,
totalPrice: this.calTotal()
})
}
}
allChose = e => {
const checked = e.target.checked;
const { arr } = this.state;
this.setState({
allChecked: checked
})
arr.map(e => e.checked = checked)
this.setState({
arr,
totalPrice: this.calTotal()
})
if (checked) {
this.checkNum = arr.length;
} else {
this.checkNum = 0
}
}
test = () => {
console.log('');
}
addNum = (e) => {
const { arr } = this.state;
arr.forEach(k => {
if (k.id === e.id) {
k.num = e.num + 1
}
})
this.setState({
arr,
totalPrice: this.calTotal()
})
}
subNum = e => {
const { arr } = this.state;
arr.forEach(k => {
if (k.id === e.id && e.num > 1) {
k.num = e.num - 1
}
})
this.setState({
arr,
totalPrice: this.calTotal()
})
}
render() {
const { arr } = this.state;
return (
<div className='Box'>
<li>
<input type="checkbox" style={{ marginRight: '10px' }} checked={this.state.allChecked} onChange={this.allChose} />全选
</li>
{
arr.map(e =>
<li key={e.id}>
<input type="checkbox" style={{ marginRight: '10px' }} checked={e.checked || false} onChange={(event) => this.itemChange(event, e)} />
<span>{`商品名称:${e.goodName}`}</span>
<span>{`单价:${e.goodPrice}`}</span>
<button onClick={() => this.subNum(e)}>-</button>
<input type="text" className='num_box' value={e.num} onChange={this.test} />
<button onClick={() => this.addNum(e)}>+</button>
</li>
)
}
<div className='foot'>
<p style={{ fontSize: '18px', textAlign: 'right' }}>{`结算: ¥${this.state.totalPrice}`}</p>
</div>
</div>
)
}
}
我的实现思路:
1、首先在state状态中增加totalPrice属性,并将它的初值设置为0;
2、创建一个calTotal函数用来计算总价;
calTotal逻辑:接收一个数据(在这里为数组),并在函数体中判断,如果传入的有数据那么就使用传入的数组,否则将state中的数据拿出进行处理,将数组中checked为true的对象取出处理:numgoodPrice 并赋值给total, 最终函数体返回最终的total*
3、在每一次的加减、选中等操作的最后调用计算calTotal函数
calTotal函数展示如下:
calTotal = cartList => {
if (!cartList) {cartList = this.state.arr}
let total = 0;
cartList.forEach(e => {
if (e.checked) {
total += e.num * e.goodPrice
}
})
return total
}
4、最后在相应的的操作之后调用这个函数,更新到state最终渲染到页面(具体见样式代码)