从零构建跨端电商小程序:Taro + React + TypeScript 实战
·
从零构建跨端电商小程序:Taro + React + TypeScript 实战
项目概述
本文将介绍一个基于 Taro 4.x 构建的跨端电商小程序项目。该项目实现了完整的电商核心功能,包括首页展示、商品分类、购物车管理等模块,支持微信小程序、H5 等多端运行。
技术栈
| 技术 | 版本 | 用途 |
|---|---|---|
| Taro | 4.1.9 | 跨端开发框架 |
| React | 18.x | 前端 UI 框架 |
| TypeScript | 5.x | 类型安全 |
| Zustand | 4.x | 状态管理 |
| SCSS | - | 样式预处理器 |
| Classnames | 2.x | CSS 类名管理 |
项目架构
src/
├── components/ # 公共组件
│ ├── ProductCard/ # 商品卡片组件
│ └── SearchBar/ # 搜索栏组件
├── data/ # 模拟数据
│ ├── banners.ts # 轮播图数据
│ ├── categories.ts # 分类数据
│ └── products.ts # 商品数据
├── pages/ # 页面
│ ├── home/ # 首页
│ ├── category/ # 分类页
│ ├── cart/ # 购物车页
│ ├── mine/ # 我的页
│ └── detail/ # 详情页
├── store/ # 状态管理
│ └── cartStore.ts # 购物车状态
├── styles/ # 全局样式
│ ├── theme.scss # 主题变量
│ └── variables.scss # CSS 变量
└── types/ # TypeScript 类型定义
└── index.ts # 公共类型
核心功能实现
1. 首页模块
首页是电商小程序的核心入口,包含多个功能区域:
// 首页核心代码 - src/pages/home/index.tsx
const HomePage = () => {
const hotProducts = getHotProducts();
const newProducts = getNewProducts();
return (
<View className={styles.container}>
<SearchBar placeholder="搜索手机、平板、配件..." />
<Swiper autoplay circular interval={3000}>
{banners.map(banner => (
<SwiperItem key={banner.id}>
<Image src={banner.image} mode="aspectFill" />
</SwiperItem>
))}
</Swiper>
<View className={styles.categorySection}>
{categories.map(category => (
<View key={category.id} onClick={() => handleCategoryClick(category.id)}>
<Text>{category.name}</Text>
</View>
))}
</View>
<View className={styles.productGrid}>
{hotProducts.map(product => (
<ProductCard key={product.id} product={product} />
))}
</View>
</View>
);
};
首页主要包含:
- 搜索栏:支持商品搜索(预留接口)
- 轮播图:自动播放,循环展示促销活动
- 分类导航:横向滚动,快速跳转分类页
- 热门推荐:网格布局展示热门商品
- 新品上市:横向滚动展示新品
2. 购物车状态管理
采用 Zustand 作为轻量级状态管理方案,实现购物车的完整功能:
// 购物车状态 - src/store/cartStore.ts
export const useCartStore = create<CartStore>((set, get) => ({
items: [],
addItem: (product, quantity = 1) => {
set((state) => {
const existingItem = state.items.find(item => item.product.id === product.id);
if (existingItem) {
return {
items: state.items.map(item =>
item.product.id === product.id
? { ...item, quantity: item.quantity + quantity }
: item
)
};
}
return {
items: [...state.items, { product, quantity, selected: true }]
};
});
},
getTotalPrice: () => {
const { items } = get();
return items
.filter(item => item.selected)
.reduce((total, item) => total + item.product.price * item.quantity, 0);
}
}));
购物车核心功能:
- 添加商品:自动合并相同商品,更新数量
- 数量增减:支持手动调整商品数量
- 单选/全选:支持单个或批量选择商品
- 价格计算:实时计算选中商品总价
- 清空购物车:一键清空所有商品
3. 商品卡片组件
商品卡片是复用率最高的组件,展示商品的核心信息:
// 商品卡片组件 - src/components/ProductCard/index.tsx
const ProductCard = ({ product, className }: ProductCardProps) => {
const handleClick = () => {
Taro.navigateTo({
url: `/pages/detail/index?id=${product.id}`
});
};
return (
<View className={classnames(styles.card, className)} onClick={handleClick}>
<Image src={product.image} mode="aspectFill" />
<View className={styles.info}>
<Text className={styles.name}>{product.name}</Text>
<Text className={styles.desc}>{product.description}</Text>
<View className={styles.tags}>
{product.tags?.map(tag => (
<View key={tag} className={styles.tag}>
<Text>{tag}</Text>
</View>
))}
</View>
<View className={styles.priceRow}>
<Text className={styles.price}>¥{product.price}</Text>
{product.originalPrice && (
<Text className={styles.originalPrice}>¥{product.originalPrice}</Text>
)}
</View>
</View>
</View>
);
};
组件特性:
- 响应式设计:适配不同屏幕尺寸
- 标签展示:新品、热卖等标签
- 价格对比:显示现价和原价,突出优惠
- 点击跳转:跳转到商品详情页
类型安全设计
使用 TypeScript 定义完整的类型系统:
// 类型定义 - src/types/index.ts
export interface Product {
id: string;
name: string;
price: number;
originalPrice?: number;
image: string;
description?: string;
sales?: number;
categoryId: string;
tags?: string[];
isNew?: boolean;
isHot?: boolean;
}
export interface CartItem {
product: Product;
quantity: number;
selected: boolean;
}
类型系统优势:
- 编译时检查:提前发现类型错误
- 代码提示:IDE 智能补全
- 文档化:类型定义即文档
多端构建配置
Taro 支持一键构建多端应用:
// package.json 构建脚本
{
"scripts": {
"dev:weapp": "taro build --type weapp --watch",
"dev:h5": "taro build --type h5 --watch",
"build:weapp": "taro build --type weapp",
"build:h5": "taro build --type h5"
}
}
支持的平台:
- ✅ 微信小程序
- ✅ H5
- ✅ 支付宝小程序
- ✅ 百度小程序
- ✅ 抖音/头条小程序
开发实践总结
1. 组件化开发
将通用 UI 抽离为独立组件,提高代码复用率:
ProductCard:商品卡片展示SearchBar:搜索栏组件
2. 状态管理策略
使用 Zustand 管理全局状态:
- 轻量级,无繁琐配置
- 支持 TypeScript
- 中间件机制灵活
3. 样式方案
采用 SCSS 模块化方案:
- 全局变量统一管理主题色
- 组件样式独立,避免冲突
- 支持嵌套、混入等高级特性
4. 数据模拟
开发阶段使用本地数据模拟:
- 快速验证功能逻辑
- 降低对后端的依赖
- 便于单元测试
总结
通过这个项目,我们展示了如何使用 Taro + React + TypeScript 构建一个完整的跨端电商小程序。项目结构清晰,代码规范,具备良好的可扩展性和维护性。
项目亮点:
- 现代化技术栈,紧跟前端趋势
- 完整的电商核心功能
- 类型安全,减少运行时错误
- 多端适配,一份代码多端运行
如果您对这个项目感兴趣,可以克隆代码进行二次开发,或作为学习 Taro 框架的参考案例。
这篇博客详细介绍了项目的技术栈、架构设计和核心功能实现,突出了 Taro 跨端开发的优势和现代前端最佳实践。
更多推荐




所有评论(0)