一、構造函數
構造一個商品類Item,然后利用foreach函數循環渲染
class Item {name: stringimage: ResourceStrprice: numberdiscount: numberconstructor(name: string, image: ResourceStr, price: number, discount: number = 0) {this.name = name;this.image = image;this.price = price;this.discount = discount;}
}//格式化代碼快捷鍵 CTRL + ALT + L
@Entry
@Component
struct Index {@State//商品數據private items: Array<Item> = [new Item('測試1', $r('app.media.head'), 1122, 122),new Item('test2', $r('app.media.startIcon'), 65),new Item('測試3', $r('app.media.background'), 120)]build() { // UI描述,內部聲明式UI結構Column({ space: 10 }) {Row() {Text("商品列表").fontWeight(FontWeight.Bold).fontSize(24)}.width('100%').margin({ bottom: 10 })ForEach(this.items,(item: Item) => {Row({ space: 8 }) {Image(item.image).width(100)Column({ space: 4 }) {Text(item.name).fontSize(20).fontWeight(FontWeight.Bold)if (item.discount) {Text('原件:¥' + item.price).fontSize(14).fontColor('#ccc').decoration({ type: TextDecorationType.LineThrough })Text('折扣價:¥' + (item.price - item.discount)).fontSize(16).fontColor('#F36')Text('補貼:¥' + item.discount).fontSize(16).fontColor('#F36')} else {Text('¥' + item.price).fontSize(16).fontColor('#F36')}}.alignItems(HorizontalAlign.Start)}.padding(10).borderRadius(10).width('100%').shadow(ShadowStyle.OUTER_DEFAULT_SM).backgroundColor('#fff')})}.backgroundColor('#f0f8ff').padding(20).width('100%').height('100%')}
}
二、布局組件List
上述商品列表案例有個致命缺陷——列表超出頁面后不可滑動。
List組件不僅可以解決這個問題,還自帶編輯、側滑、分組等功能,在移動端開發中很方便
可參考:
創建列表 (List)-ArkUI官網文檔
在案例for循環部分加上List
List() {ForEach(this.items, (item: Item) => {ListItem() {Row({ space: 8 }) {Image(item.image).width(100)Column({ space: 4 }) {Text(item.name).fontSize(20).fontWeight(FontWeight.Bold)if (item.discount) {Text('原件:¥' + item.price).fontSize(14).fontColor('#ccc').decoration({ type: TextDecorationType.LineThrough })Text('折扣價:¥' + (item.price - item.discount)).fontSize(16).fontColor('#F36')Text('補貼:¥' + item.discount).fontSize(16).fontColor('#F36')} else {Text('¥' + item.price).fontSize(16).fontColor('#F36')}}.alignItems(HorizontalAlign.Start)}.padding(10).borderRadius(10).width('100%').shadow(ShadowStyle.OUTER_DEFAULT_SM).backgroundColor('#fff')}.margin(5)})}.width('100%')
寫在最后:
ArkUI對于有前端基礎的同學來說比較容易上手,類似于antdUI和elementUI雖然有的寫法不同,但華為提供的devEco編輯器自帶提示和鼠標懸浮文檔查詢功能,檢索用法很方便
上一篇 鴻蒙開發HarmonyOS NEXT (一) 入門-CSDN博客