学习目标:
ArkUI(HarmonyOS应用开发框架)中创建一个包含商品列表的页面,以及如何定义和复用组件(如标题组件GTitle和商品卡片组件ProductCard)。
项目源码:https://gitee.com/migangxiaozi/hongmeng-learning
数据模型定义:
提示:首先,定义了一个Item接口来描述商品的数据结构,这有助于提高代码的可读性和可维护性。
export interface Item {
discount: number;
imagesrc: string | PixelMap | Resource;
title: string;
price: string;
}
组件设计:
提示:将可重复使用的内容封装成组件,这有助于提高代码的可读性和可维护性。
标题组件 (GTitle)
接收一个标题字符串资源title,并以特定样式显示。
@Component
export struct GTitle {
private title:ResourceStr
build() {
Row(){
Column(){
Text(this.title)
.fontSize(30)
.fontColor('#FFFFFFFFF')
.fontWeight(FontWeight.Bolder)
}
}
.height(30);
}
}
商品卡片组件 (ProductCard)
接收一个Item类型的对象item,根据商品是否打折展示不同的信息布局。
@Component
// 定义 ProductCard 组件
export struct ProductCard {
private item: Item
// 组件实现
build() {
Row({ space: 6 }) {
Image(this.item.imagesrc)
.width(100)
.interpolation(ImageInterpolation.High)
Column({ space: 4 }) {
if (this.item.discount) {
Text(this.item.title)
.fontSize(20)
.fontWeight(FontWeight.Bolder)
Text(`原价 ${this.item.price}`)
.fontColor('#ff948086')
.fontSize(18)
.decoration({ type: TextDecorationType.LineThrough, color: '#ffd42121' })
Text(`折扣 ${this.item.discount}`)
.fontColor('#F36')
.fontSize(18)
Text(`折扣价 ${ Number(this.item.price) - Number(this.item.discount)}`)
.fontColor('#F36')
.fontSize(18)
} else {
Text(this.item.title)
.fontSize(20)
.fontWeight(FontWeight.Bolder)
Text(`$ ${this.item.price}`)
.fontColor('#F36')
.fontSize(18)
}
}
.width('60%')
.alignItems(HorizontalAlign.Start)
.justifyContent(FlexAlign.Start)
.backgroundImageSize(ImageSize.Auto)
.align(Alignment.TopStart)
}
.borderRadius(20)
.backgroundColor('#FFFFFF')
}
}
页面结构与逻辑:
使用createItemOptions方法动态生成模拟的商品数据数组,每个商品包含图片、标题、折扣和价格信息。
使用Column组件作为主容器,设置间距。 添加GTitle组件展示页面标题。 利用List和ForEach循环渲染ProductCard组件,展示每个商品详情
import App from '@system.app'
import {Item} from '../config/type'
import {GTitle,ProductCard} from '../compent/GoodListTitle'
// 定义Item类型,提高代码的可读性和可维护性
@Entry
@Component
struct Index {
itemOptions: Item[] = this.createItemOptions();
private createItemOptions(): Item[] {
let arr = [];
for (let i = 0; i < 100; i++) {
arr.push({
imagesrc: $r('app.media.icon'),
title: `ProductCard组件 ${i}`,
discount: i%2==0?Math.floor(Math.random() * (100 - 1 + 1)).toFixed(0):0,
price: (Math.floor(Math.random() * (9999 - 100 + 1)).toFixed(0))
})
}
return arr;
}
build() {
Column({space:8}) {
GTitle({title:'组件title'})
.margin(10)
List({space:20}){
ForEach(
this.itemOptions,
(item:any,index?:number)=>{
ListItem(){
ProductCard({item:item})
}}
)
}
.width('100%')
.layoutWeight(1)
.alignListItem(ListItemAlign.Center)
}
.width('100%')
.height('100%')
.backgroundColor('#ffdde3e7')
}
}
心得:
尽管ArkUI(HarmonyOS应用开发框架)的语法与传统的HTML+JS有显著差异,但它们在构建UI时的一些核心思想是相通的。
声明式编程风格
- HTML+JS:
在传统的Web开发中,HTML负责声明页面结构,而JavaScript用来添加交互逻辑。这种分离使得开发者可以专注于描述“页面应该长什么样子”,而不是“页面如何变化”。 - ArkUI:
类似地,ArkUI采用了声明式编程模型。通过.width(‘100%’)、.height(‘100%’)这样的链式调用来声明组件的样式和布局,而非直接操作DOM或状态变更。
尽管有这些相似之处, ArkUI作为面向HarmonyOS的应用开发框架,它更加强调声明式组件、状态管理和平台级别的集成,而不仅仅是DOM操作。