Harmonyos5应用开发实战——卡片组件的交互与展示
文章内容概要
本文聚焦于HarmonyOS 5应用开发中一个卡片组件的实现。该组件会根据订单状态展示不同的卡片样式,包括普通卡片和订单卡片。同时,组件提供了丰富的交互功能,如点击卡片跳转到指定页面,为用户提供了便捷的操作体验。
核心功能介绍
1. 组件初始化与状态判断
组件使用 @Entry 装饰器进行初始化,并通过 @LocalStorageProp 从本地存储中获取相关数据,如店铺名称、订单状态、订单ID等。在 build 方法中,根据 orderState 的值判断展示普通卡片还是订单卡片。
@Entry(storageUpdateByMsg)
@Component
struct WidgetCard {
@LocalStorageProp('storeName') storeName: ResourceStr = $r('app.string.storeName');
@LocalStorageProp('orderState') orderState: boolean = false;
@LocalStorageProp('orderId') orderId: string = '';
// 其他属性...
build() {
if (this.orderState) {
this.orderCard();
} else {
this.normalCard();
}
}
}
2. 普通卡片展示
普通卡片包含店铺标题和一组图片列表,底部有一个“下单”按钮。点击卡片或按钮会触发 postCardAction 方法,跳转到指定页面。
@Builder
normalCard() {
Column() {
this.storeTitle();
List({ space: 8 }) {
ListItem() {
Image($r('app.media.ic_card_img1')).width(52).height(52).borderRadius(8);
};
// 其他图片列表项...
}.listDirection(Axis.Horizontal).margin({ top: 12 }).layoutWeight(1).scrollBar(BarState.Off);
Row() {
Text($r('app.string.order'))
.fontSize($r('sys.float.Body_S'))
.fontWeight(FontWeight.Medium)
.fontColor($r('sys.color.comp_background_list_card'))
}
.margin({ top: 14 })
.padding({
top: 4,
bottom: 4,
})
.justifyContent(FlexAlign.Center)
.width(this.FULL_PERCENT)
.borderRadius(14)
.linearGradient({
direction: GradientDirection.Bottom,
colors: [['#FFBB81', 0], ['#EC710B', 1]],
})
.onClick(() => {
postCardAction(this, {
action: this.ACTION_TYPE,
abilityName: this.ABILITY_NAME,
params: { targetPage: 'funB' },
});
});
}
.width(this.FULL_PERCENT)
.height(this.FULL_PERCENT)
.displayPriority(this.DISPLAY_PRIORITY_ONE)
.flexGrow(this.FLEX_GROW_VALUE)
.padding(12)
.onClick(() => {
postCardAction(this, {
action: this.ACTION_TYPE,
abilityName: this.ABILITY_NAME,
params: { targetPage: 'funB' },
});
});
}