#跟着晓明学鸿蒙# GridRow组件实现电商首页商品展示
·

目录
- 案例介绍
- 代码实现
- 1. 商品数据定义
- 2. 商品展示实现
- 代码详解
- 1. 响应式布局设计
- 2. 商品卡片设计
- 3. 样式优化
- 总结
案例介绍
本篇文章将介绍如何使用GridRow组件实现电商首页的商品展示功能。通过网格布局展示热门商品和推荐商品,包含商品图片、标题、价格等信息的展示。
代码实现
1. 商品数据定义
// 商品信息
interface Product {
id: number;
title: string;
imageUrl: string;
price: number;
originalPrice?: number;
sales: number;
tags?: string[];
}
@Entry
@Component
struct ECommerceHomePage {
// 热门商品数据
@State hotProducts: Product[] = [
{
id: 1,
title: '超薄笔记本电脑',
imageUrl: 'https://example.com/product1.jpg',
price: 4999,
originalPrice: 5999,
sales: 1200,
tags: ['新品', '热卖']
},
// ... 更多商品数据
];
}
2. 商品展示实现
@Builder
renderHotProducts() {
Column() {
Row() {
Text('热门商品')
.fontSize(18)
.fontWeight(FontWeight.Bold)
Blank()
Text('查看更多 >')
.fontSize(14)
.fontColor('#FF5722')
.onClick(() => {
// 跳转到更多热门商品页面
})
}
.width('100%')
.padding({ left: 16, right: 16 })
// 使用GridRow实现商品网格
GridRow({
columns: this.windowWidth <= 600 ? 2 : 3, // 根据窗口宽度调整列数
gutter: 16
}) {
ForEach(this.hotProducts, (product: Product) => {
GridItem() {
this.renderProductCard(product)
}
})
}
.width('100%')
.padding({ left: 16, right: 16, top: 8, bottom: 8 })
}
}
// 渲染商品卡片
@Builder
renderProductCard(product: Product) {
Column() {
// 商品图片
Stack({ alignContent: Alignment.TopEnd }) {
Image(product.imageUrl)
.width('100%')
.aspectRatio(1)
.objectFit(ImageFit.Cover)
.borderRadius({ topLeft: 8, topRight: 8 })
// 商品标签
if (product.tags && product.tags.length > 0) {
Text(product.tags[0])
.fontSize(12)
.fontColor(Color.White)
.backgroundColor('#FF5722')
.padding({ left: 6, right: 6, top: 2, bottom: 2 })
.borderRadius(4)
.margin(8)
}
}
.width('100%')
// 商品信息
Column() {
// 商品标题
Text(product.title)
.fontSize(14)
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.width('100%')
// 商品价格
Row({ space: 4 }) {
Text(`¥${product.price}`)
.fontSize(16)
.fontColor('#FF5722')
.fontWeight(FontWeight.Bold)
if (product.originalPrice) {
Text(`¥${product.originalPrice}`)
.fontSize(12)
.fontColor('#999999')
.decoration({ type: TextDecorationType.LineThrough })
}
}
.width('100%')
.margin({ top: 4 })
// 销量
Text(`已售${product.sales}件`)
.fontSize(12)
.fontColor('#999999')
.width('100%')
.margin({ top: 4 })
}
.width('100%')
.padding(8)
}
.width('100%')
.backgroundColor(Color.White)
.borderRadius(8)
.onClick(() => {
// 跳转到商品详情页
})
}
代码详解
1. 响应式布局设计
GridRow({
columns: this.windowWidth <= 600 ? 2 : 3, // 根据窗口宽度调整列数
gutter: 16
})
商品展示的响应式设计:
- 小屏幕(≤600px):显示2列
- 大屏幕(>600px):显示3列
- 统一的商品间距设置
2. 商品卡片设计
商品卡片包含四个部分:
- 商品图片:使用aspectRatio保持1:1比例
- 商品标签:右上角显示标签信息
- 商品标题:最多显示两行,超出部分省略
- 价格信息:包含现价、原价和销量
3. 样式优化
样式设计要点:
- 圆角设计:增加视觉美感
- 价格颜色:使用品牌色突出显示
- 原价样式:使用删除线和灰色显示
- 统一的内边距:确保内容布局整齐
总结
本篇文章展示了如何使用GridRow组件实现电商首页的商品展示功能。通过响应式设计和精心的样式处理,创建了美观实用的商品卡片布局。这种实现方式不仅能够适应不同屏幕尺寸,还能为用户提供清晰的商品信息展示,是电商应用中常用的布局方案。
更多推荐




所有评论(0)