#鸿蒙通关秘籍#在HarmonyOS NEXT中如何基于数组实现循环渲染?

HarmonyOS
2024-11-27 13:10:02
993浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
hm673ff05a1270a

在HarmonyOS NEXT中,可以使用ForEach接口基于数组类型的数据实现循环渲染。需配合使用容器组件。

import text from '@ohos.graphics.text';

interface newItem{
  title: string,
  subTitle: string,
  time: string
}

@Entry
@Component
struct Index {
  @State news: newItem[] = [
    {
      title: '新闻标题1',
      subTitle: '这是一个副标题1',
      time: '2024/7/22'
    },
    {
      title: '新闻标题2',
      subTitle: '这是一个副标题2',
      time: '2024/7/22'
    },
    {
      title: '新闻标题3',
      subTitle: '这是一个副标题3',
      time: '2024/7/22'
    }
  ];
  build() {
    Scroll(){
      Column({space:1}){
        ForEach(this.news,(item:newItem)=>{
          Column(){
            Row(){
              Text(item.title)
                .fontSize(22)
            }
            .width('100%')
            Row(){
              Text(item.subTitle)
                .fontColor('#aaa')
            }
            .width('100%')
            Row(){
              Text(item.time)
                .fontColor('#aaa')
            }
            .width('100%')
            .justifyContent(FlexAlign.End)
          }
          .padding(10)
          .border({
            width: {
              bottom: 1
            },
            color: '#ccc',
            style: BorderStyle.Dashed,
          })
          .backgroundColor('rgba(25, 159, 126, 0.1)')
        },(item:newItem,index:number)=>index+'')
      }
      .width('100%')
      .backgroundColor('#eee')
    }
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.

该代码展示了如何通过循环渲染新闻列表。


分享
微博
QQ
微信
回复
2024-11-27 14:25:08


相关问题