赞
踩
ForEach函数是一个迭代函数,需要传递两个必须参数和一个可选参数。主要通过迭代来获取参数arr中的数据不断的生成单个Item来生成鸿蒙中的列表样式
通过嵌套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 : string
- image : string
- price : number
- discount : number //折扣价
-
- //构造函数
- constructor(name: string, image: string, price: number, discount?: number) {
- this.name = name
- this.image = image
- this.price = price
- this.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(
- 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}) //设置中划线
- )
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。