一、ForEach函數
ForEach函數是一個迭代函數,需要傳遞兩個必須參數和一個可選參數。主要通過迭代來獲取參數arr中的數據不斷的生成單個Item來生成鴻蒙中的列表樣式
二、先創建單個的Item的UI
通過嵌套Row與Column來實現單個Item的UI。例如圖中沒有折扣的可以看成一個Row,然后圖片在左邊,然后右邊是一個Column,然后右側Column中兩個Text組件豎向排列。(其中,borderRadius可以設置圓角)。
Row({space:3}) {Image(item.image).width(this.imageWidth).height(80).padding({left:20}).borderRadius(5)Column() {Text(item.name).fontWeight(FontWeight.Bold).fontSize(25).baselineOffset(0).height(40).width(200)Text('¥'+item.price).fontSize(17).textAlign(TextAlign.Start).fontColor("#FF0000").height(30).width(200)}.margin({left:20})}.height(130).width('90%').backgroundColor('#FFFFFF').borderRadius(20)
三、準備數據
ForEach函數需要傳遞一個數組,數組中是多個Item,可以定義一個Item類來加載數據
class Item {name : stringimage : stringprice : numberdiscount : number //折扣價//構造函數constructor(name: string, image: string, price: number, discount?: number) {this.name = namethis.image = imagethis.price = pricethis.discount = discount}
}
然后,在生成一個數組作為ForEach的第一個參數
//圖片資源
url: string = 'https://lmg.jj20.com/up/allimg/1114/0406210Z024/2104060Z024-5-1200.jpg'private items:Array<Item> = [new Item('華為',this.url,3456),new Item('遙遙領先',this.url,56,15),new Item('很吊啊',this.url,3756,500),new Item('列表',this.url,9456),new Item('產品',this.url,4456),new Item('很吊啊',this.url,3456),new Item('列表',this.url,3456),]
四、使用ForEach迭代
ForEach(this.items,//默認item是any類型的,所以想要獲取item屬性值提示,可以給item設置類型Item(item : Item) => {if (item.discount) {//加載有折扣的UI} else {//加載沒有折扣的UI}})
五、其他
想要實現Text的中劃線,可以使用屬性decoration裝飾器,這個屬性可以設置上劃線、中劃線、下劃線等等
Text('原價 ¥'+item.price).fontSize(17).textAlign(TextAlign.Start).fontColor("#000000").height(30).margin({right:10}.decoration({type:TextDecorationType.LineThrough}) //設置中劃線)