You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用React构建带购物车和商品列表的简单页面

实现方案(React 商品列表+购物车功能)

核心实现思路

  • 轻量场景直接用React内置的useState做状态管理即可,不需要引入额外状态库,维护两个核心数据:静态商品列表、购物车数据(用对象存储,键为商品id,值为对应购买数量)
  • 提前写死6-7条模拟商品数据,包含id、名称、价格等必要字段即可
  • 每个商品卡片配置加减操作按钮,点击分别触发购物车数量的增减逻辑,数量为0时减号按钮自动置灰避免出现负数
  • 顶部新增购物车统计区域,实时展示已选商品总数量、总金额

完整可运行代码示例

import { useState } from 'react';

// 模拟7个商品数据,可按需修改字段
const mockProducts = [
  { id: 1, name: '无线蓝牙耳机', price: 199 },
  { id: 2, name: '快充移动电源', price: 89 },
  { id: 3, name: '桌面手机支架', price: 29.9 },
  { id: 4, name: '笔记本散热器', price: 79 },
  { id: 5, name: 'PBT键帽套装', price: 129 },
  { id: 6, name: '屏幕清洁喷雾', price: 19.9 },
  { id: 7, name: '编织Type-C数据线', price: 15 }
];

function ProductCartPage() {
  // 购物车状态:{ 商品id: 购买数量 }
  const [cart, setCart] = useState({});

  // 增加商品购买数量
  const handleAdd = (productId) => {
    setCart(prev => ({
      ...prev,
      [productId]: (prev[productId] || 0) + 1
    }));
  };

  // 减少商品购买数量
  const handleDecrease = (productId) => {
    setCart(prev => {
      const currentCount = prev[productId] || 0;
      if (currentCount <= 1) {
        // 数量为0时移除该商品的购物车记录
        const newCart = {...prev};
        delete newCart[productId];
        return newCart;
      }
      return {
        ...prev,
        [productId]: currentCount - 1
      };
    });
  };

  // 计算购物车总商品数
  const totalCount = Object.values(cart).reduce((sum, count) => sum + count, 0);
  // 计算购物车总金额,保留两位小数
  const totalPrice = Object.entries(cart).reduce((sum, [productId, count]) => {
    const product = mockProducts.find(item => item.id === Number(productId));
    return sum + product.price * count;
  }, 0).toFixed(2);

  return (
    <div style={{ maxWidth: 1200, margin: '0 auto', padding: 20 }}>
      {/* 购物车统计栏 */}
      <div style={{ padding: 15, background: '#f5f5f5', borderRadius: 8, marginBottom: 20 }}>
        <h3>购物车</h3>
        <p>已选商品:{totalCount} 件</p>
        <p>合计金额:¥{totalPrice}</p>
      </div>

      {/* 商品列表 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
        {mockProducts.map(product => (
          <div key={product.id} style={{ border: '1px solid #eee', borderRadius: 8, padding: 15 }}>
            {/* 商品图占位,可替换为真实img标签 */}
            <div style={{ width: '100%', height: 150, background: '#f0f0f0', marginBottom: 10 }}>
              {product.name} 示意图
            </div>
            <h4>{product.name}</h4>
            <p style={{ color: '#f40', fontSize: 18 }}>¥{product.price}</p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10 }}>
              <button 
                onClick={() => handleDecrease(product.id)}
                disabled={!cart[product.id]}
                style={{ padding: '5px 12px', cursor: 'pointer' }}
              >
                -
              </button>
              <span>{cart[product.id] || 0}</span>
              <button 
                onClick={() => handleAdd(product.id)}
                style={{ padding: '5px 12px', cursor: 'pointer' }}
              >
                +
              </button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

export default ProductCartPage;

补充说明

  • 代码无额外第三方依赖,直接替换React项目的入口组件即可运行
  • 所有样式均为内联写法,可根据需求替换为CSS类、CSS Module等方案调整页面外观
  • 如需刷新页面保留购物车数据,可将cart状态同步到localStorage中做持久化存储

内容的提问来源于stack exchange,提问作者S F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:54:04