react实现一个购物车

1.结合Ant Design Mobile 实现一个底部tab栏切换(配合路由使用)

配置路由

import { Navigate } from "react-router-dom";
import Layout from '../pages/layout'
import Index from '../pages/index/index'
import Cart from '../pages/cart/cart'
import Shop from '../pages/shop/shop'
import My from '../pages/my/my'
import Detail from '../pages/detail/detail'
import Login from '../pages/login/login'

const routerList = [
    { path: '/', element: <Navigate to='/layout/index'></Navigate> },
    {
        path: "layout", element: <Layout></Layout>, children: [
            { path: 'index', element: <Index></Index> },
            { path: 'cart', element: <Cart></Cart> },
            { path: 'shop', element: <Shop></Shop> },
            { path: 'my', element: <My></My> },
            { path: 'detail', element: <Detail></Detail> },
        ]
    },
    {
        path: 'login', element: <Login></Login>
    }

]
export default routerList

layout页面

import React from 'react'
import { TabBar } from 'antd-mobile'
import { useLocation, Outlet, useNavigate } from 'react-router-dom'
import {
  AppOutline,
  MessageOutline,
  UnorderedListOutline,
  UserOutline,
} from 'antd-mobile-icons'
import './layout.css'

function Bottom() {
  const nav = useNavigate()
  const location = useLocation()
  const { pathname } = location

  const setRouteActive = (value) => {
    nav(value)
  }

  const tabs = [
    {
      key: 'index',
      title: '首页',
      icon: <AppOutline />,
    },
    {
      key: 'cart',
      title: '分类',
      icon: <UnorderedListOutline />,
    },
    {
      key: 'shop',
      title: '购物车',
      icon: <MessageOutline />,
    },
    {
      key: 'my',
      title: '我的',
      icon: <UserOutline />,
    },
  ]

  return (
    <TabBar activeKey={pathname} onChange={value => setRouteActive(value)} >
      {tabs.map(item => (
        <TabBar.Item key={item.key} icon={item.icon} title={item.title} className="active" />
      ))}
    </TabBar>
  )
}

export default () => {
  return (
    <div className="app">
      <div className="body">
        <Outlet></Outlet>
      </div>
      <div className="bottom">
        <Bottom />
      </div>
    </div>
  )
}

layout页面样式

.app {
  height: 100vh;
  display: flex;
  flex-direction: column;
}
.body {
  flex: 1;
  display: flex;
}

.bottom {
  border-top: solid 1px var(--adm-color-border);
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: white;
}

.active:hover {
  color: red;
}

首页+回到顶部效果(附加动画)

import React from 'react';
import { Swiper, Image } from 'react-vant';
import { images } from './demo/images.ts';
import { useState, useEffect } from 'react';
import axios from '../../server/request'


import './index.css'
function Index() {
    const [showTrue, setShowTrue] = useState(false)
    const [data, setData] = useState([])
    useEffect(() => {
        getGoodList()
        const handleScrool = () => {
            //滑动的距离大于 0 时,显示按钮
            document.documentElement.scrollTop > 0 ? setShowTrue(true) : setShowTrue(false)
        }
        document.addEventListener('scroll', handleScrool)
        return () => document.removeEventListener('scroll', handleScrool)


    }, [showTrue])
    // 回到顶部
    const backTop = () => {
        let timer = setInterval(() => {
            //获取滑动的距离
            let top = document.documentElement.scrollTop || document.body.scrollTop
            window.scrollTo(0, top - top / 5) //设置返回时 是缓慢带有动画的
            if (top === 0) {
                clearInterval(timer)
            }
        }, 30)
    }

    function getGoodList() {
        axios.get('/getgoodlist').then(res => {
            console.log(res, '4444444')
            setData(res.data)

        })

    }
    return (
        <div className="index">
            <div className="demo-swiper">
                <Swiper>
                    {images.map((image) => (
                        <Swiper.Item key={image}>
                            <Image src={image} style={{ height: "250px" }} />
                        </Swiper.Item>
                    ))}
                </Swiper>
            </div>
            <div className="nav">
                <ul>
                    <li>签到</li>
                    <li>礼券</li>
                    <li>砍价</li>
                    <li>专栏</li>
                </ul>

            </div>·
            <div className="second-swiper">
                <h2>精选主题</h2>
                <div className="demo-swiper">
                    <Swiper slideSize={80}> {images.map((image) => (
                        <Swiper.Item key={image}>
                            <div className='images'>
                                <Image src={image} style={{ height: "250px", }} />
                            </div>
                        </Swiper.Item>
                    ))}</Swiper>
                </div>
            </div>
            <div className="content">
                <h2>人气推荐</h2>
                <ul>
                    {
                        data.map((item, index) => {
                            return (
                                <li key={index}>
                                    <img src={item.pic} alt="" width="100%" style={{ height: "200px" }} />
                                    <p>{item.title}</p>
                                    <p style={{ color: 'red' }}>¥{item.price}</p>
                                </li>
                            )
                        })
                    }
                </ul>
            </div>
            <div className="backTop" style={{ display: showTrue ? 'block' : 'none' }} onClick={backTop}>返回顶部</div>

        </div>
    );
}
export default Index

分类页面

import { Search } from 'react-vant';
import React, { useEffect, useState } from 'react';
import { Sidebar } from 'react-vant';
import axios from '../../server/request';
import './style.css'
import { ProductCard } from 'react-vant';


export default function Cart() {
  const [value, setValue] = useState('');
  const [active, setActive] = useState(0);
  const [data, setData] = useState([])
  useEffect(() => {
    getGoodList(0)
  }, [])

  function getGoodList(v) {
    setActive(v)
    axios.get('/getGood?type=' + v).then(res => {
      console.log(res.data, '5555555555')
      setData(res.data)
    })

  }
  return (
    <div className='cart'>
      <div className="cart-search">
        <Search value={value} onChange={setValue} placeholder="请输入搜索关键词" />
      </div>
      <div className="cart-content">
        <Sidebar
          value={active}
          onChange={(v) => {
            getGoodList(v)

          }}
        >
          <Sidebar.Item contentStyle={{ backgroundColor: '#fff', padding: '18px 10px' }} title="男装">
            {
              data.map(item => {
                return (
                  <div>
                    <ProductCard
                      key={item._id}
                      price={item.price}
                      title={item.name}
                      thumb={item.img}
                    />
                  </div>
                )
              })
            }
          </Sidebar.Item>
          <Sidebar.Item contentStyle={{ backgroundColor: '#fff', padding: '18px 10px' }} title="女装">
            {
              data.map(item => {
                return (
                  <div>
                    <ProductCard
                      key={item._id}
                      price={item.price}
                      title={item.name}
                      thumb={item.img}
                    />
                  </div>
                )
              })
            }
          </Sidebar.Item>
          <Sidebar.Item contentStyle={{ backgroundColor: '#fff', padding: '18px 10px' }} title="童装">
            {
              data.map(item => {
                return (
                  <div>
                    <ProductCard
                      key={item._id}
                      price={item.price}
                      title={item.name}
                      thumb={item.img}
                    />
                  </div>
                )
              })
            }
          </Sidebar.Item>
        </Sidebar>

      </div>
    </div>
  )
}

详情页面

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用React的状态来实现全选反选购物车功能。 首先,你需要定义一个组件,例如 `ShoppingCart` 组件,它包含多个 `CartItem` 子组件。每个 `CartItem` 组件都有一个 `checked` 属性,表示该商品是否被选中。 在 `ShoppingCart` 组件中,需要定义一个 `selectedAll` 状态,表示是否全选。同时,还需要定义一个 `handleSelectAll` 函数,用于处理全选/反选功能。该函数将会通过 `onChange` 事件绑定到全选的复选框上。 以下是示例代码: ```jsx import React, { useState } from "react"; const ShoppingCart = ({ items }) => { const [selectedAll, setSelectedAll] = useState(false); // 处理全选/反选 const handleSelectAll = () => { setSelectedAll(!selectedAll); }; // 处理子组件的选中状态改变 const handleItemChange = (index, checked) => { // TODO: 更新 items[index] 的选中状态 }; return ( <div> <label> <input type="checkbox" checked={selectedAll} onChange={handleSelectAll} /> 全选 </label> {items.map((item, index) => ( <CartItem key={index} item={item} checked={item.checked} onChange={handleItemChange} /> ))} </div> ); }; const CartItem = ({ item, checked, onChange }) => { const handleItemChange = (event) => { onChange(item.id, event.target.checked); }; return ( <div> <label> <input type="checkbox" checked={checked} onChange={handleItemChange} /> {item.name} </label> </div> ); }; ``` 在 `ShoppingCart` 组件中,我们通过 `map` 方法遍历所有的商品,并渲染 `CartItem` 子组件。在 `CartItem` 组件中,我们通过 `checked` 和 `onChange` 属性来控制选中状态和处理状态改变。 在 `handleSelectAll` 函数中,我们使用 `setSelectedAll` 来更新 `selectedAll` 状态。在 `handleItemChange` 函数中,我们需要更新 `items` 数组中对应商品的选中状态。你可以通过 `useState` 状态管理库来管理 `items` 数组的状态,或者通过 `Redux` 等状态管理工具来管理状态。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值