import React, { useState } from 'react';
import Product from './Product';
const Cart = () => {
const [items, setItems] = useState([]);
const addToCart = (product) => {
setItems([...items, product]);
};
const removeFromCart = (productId) => {
setItems(items.filter((item) => item.id !== productId));
};
const totalPrice = items.reduce((total, item) => {
return total + item.price;
}, 0);
return (
<div>
<h2>Your Cart</h2>
{items.length === 0 ? (
<p>Your cart is empty.</p>
) : (
<ul>
{items.map((item) => (
<li key={item.id}>
{item.name} - ₹{item.price}
<button onClick={() => removeFromCart(item.id)}>Remove</button>
</li>
))}
</ul>
)}
<p>Total Price: ₹{totalPrice}</p>
</div>
);
};
export default Cart;
这个简单的购物车组件使用React的函数组件和Hooks (useState
) 来管理购物车的状态。它包含添加商品到购物车、从购物车移除商品以及计算购物车商品总价的功能。这个例子可以作为学习React状态管理和组件逻辑的起点。