您现在的位置是:网站首页> 编程资料编程资料
react通过组件拆分实现购物车界面详解_React_
2023-05-24
363人已围观
简介 react通过组件拆分实现购物车界面详解_React_
页面组件拆分图

功能点
- 实现全选反选
- 数量的增加和减少
- 选中删除,单独删除
- 商品总价和商品总数量的变化
首先在根组件中把页面的布局以及功能先实现,然后再拆分组件,最后通过组件传值进行属性和方法的传递
代码展示
app.js组件
import axios from 'axios'; import React, { Component } from 'react'; import './App.css'; import Cartfoot from './Component/Cartfoot'; import CartList from './Component/CartList'; export default class App extends Component { constructor() { super() this.state = { list: [], checked:false } this.getCart() } getCart = async () => { let res = await axios.get('http://127.0.0.1:3002/getCart') console.log(res.data.data); let carts = res.data.data carts.map(item => { return item.checked = false }) this.setState({ list: carts }) } // 全选 qx=(e)=>{ let {list}=this.state list.map(item=>item.checked=e.target.checked) this.setState({ list:list, checked:e.target.checked }) } // 反选 fx=(index)=>{ let {list}=this.state list[index].checked = !list[index].checked this.setState({ list:list, checked:list.every(item=>item.checked) }) } // 选中删除 checkDel=()=>{ let {list}=this.state let delAll=list.filter(item=>!item.checked) this.setState({ list:[...delAll] }) } // 数量加减操作 handlerNum=(index,type="jia")=>{ let {list}=this.state type==='jia'?list[index].num++ :list[index].num-- this.setState({ list:list }) } // 计算操作 count=()=>{ let total=0 let nums=0 let {list}=this.state list.forEach(item=>{ if(item.checked){ total+=item.num*item.prize nums+=item.num } }) return [total,nums] } // 删除按钮 Del=(index)=>{ let {list}=this.state list.splice(index,1) this.setState({ list:list }) } render() { let { list ,checked} = this.state return ( ID 名字 图片 价格 数量 操作
) } }在app组件中,我们把所有的方法和请求到的数据接口写在这里,然后再通过props属性进行组件间的通信
CartList.js组件
import React from 'react' import CartItem from './CartItem' export default function CartList(props) { return ( // { props.list.map((item, index) => { return ( ) }) } // ) }上面的{...props}是因为组件在传递属性时,如果传递的时候是一个对象属性,我们可以使用扩展运算符传递数据
Cartfoot.js组件
import React from 'react' export default function Cartfoot(props) { return ( 商品总价格:{props.count()[0]} 商品总数量:{props.count()[1]} ) }CartItem.js组件
import React from 'react' import CartColltract from './CartColltract' export default function CartItem(props) { let {item,index}=props return ( props.fx(index)}/> {item._id} {item.name} 
{item.prize} ) }CartColltract.js组件
import React from 'react' export default function CartColltract(props) { let {index,item}=props return ( ) }像我们上面组件那样,组件之间层层嵌套,我们不仅可以使用普通父传子,子传父的组件通信方式进行组件传值,也可以使用context兄弟组件通信
到此这篇关于react通过组件拆分实现购物车界面详解的文章就介绍到这了,更多相关react组件拆分内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
您可能感兴趣的文章:
