当前位置:   article > 正文

鸿蒙开发组件之ForEach列表_鸿蒙foreach

鸿蒙foreach

一、ForEach函数

ForEach函数是一个迭代函数,需要传递两个必须参数和一个可选参数。主要通过迭代来获取参数arr中的数据不断的生成单个Item来生成鸿蒙中的列表样式

二、先创建单个的Item的UI

通过嵌套Row与Column来实现单个Item的UI。例如图中没有折扣的可以看成一个Row,然后图片在左边,然后右边是一个Column,然后右侧Column中两个Text组件竖向排列。(其中,borderRadius可以设置圆角)。

  1. Row({space:3}) {
  2. Image(item.image)
  3. .width(this.imageWidth)
  4. .height(80)
  5. .padding({left:20})
  6. .borderRadius(5)
  7. Column() {
  8. Text(item.name)
  9. .fontWeight(FontWeight.Bold)
  10. .fontSize(25)
  11. .baselineOffset(0)
  12. .height(40)
  13. .width(200)
  14. Text('¥'+item.price)
  15. .fontSize(17)
  16. .textAlign(TextAlign.Start)
  17. .fontColor("#FF0000")
  18. .height(30)
  19. .width(200)
  20. }
  21. .margin({left:20})
  22. }.height(130)
  23. .width('90%')
  24. .backgroundColor('#FFFFFF')
  25. .borderRadius(20)

三、准备数据

ForEach函数需要传递一个数组,数组中是多个Item,可以定义一个Item类来加载数据

  1. class Item {
  2. name : string
  3. image : string
  4. price : number
  5. discount : number //折扣价
  6. //构造函数
  7. constructor(name: string, image: string, price: number, discount?: number) {
  8. this.name = name
  9. this.image = image
  10. this.price = price
  11. this.discount = discount
  12. }
  13. }

然后,在生成一个数组作为ForEach的第一个参数

  1. //图片资源
  2. url: string = 'https://lmg.jj20.com/up/allimg/1114/0406210Z024/2104060Z024-5-1200.jpg'
  3. private items:Array<Item> = [
  4. new Item('华为',this.url,3456),
  5. new Item('遥遥领先',this.url,56,15),
  6. new Item('很吊啊',this.url,3756,500),
  7. new Item('列表',this.url,9456),
  8. new Item('产品',this.url,4456),
  9. new Item('很吊啊',this.url,3456),
  10. new Item('列表',this.url,3456),
  11. ]

四、使用ForEach迭代

  1. ForEach(
  2. this.items,
  3. //默认item是any类型的,所以想要获取item属性值提示,可以给item设置类型Item
  4. (item : Item) => {
  5. if (item.discount) {
  6. //加载有折扣的UI
  7. } else {
  8. //加载没有折扣的UI
  9. }
  10. }
  11. )

五、其他

想要实现Text的中划线,可以使用属性decoration装饰器,这个属性可以设置上划线、中划线、下划线等等

  1. Text('原价 ¥'+item.price)
  2. .fontSize(17)
  3. .textAlign(TextAlign.Start)
  4. .fontColor("#000000")
  5. .height(30)
  6. .margin({right:10}
  7. .decoration({type:TextDecorationType.LineThrough}) //设置中划线
  8. )

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/231499?site
推荐阅读
相关标签
  

闽ICP备14008679号