Image description

这个案例当中涉及到知识内容:

  1. 对象类型使用 Interface 约束

  2. 华为内容的资源类型 Resource

  3. 定义数组类型的数据 FansItem[]

  4. 使用 ForEach 完成循环渲染

  5. 使用 @Extend 扩展组件属性方法

具体代码如下:

interface FansItem {
  avatar: Resource
  name: string
  title: string
  isFollow: boolean
}

@Entry
@Component
struct TestPage {
  playerList: FansItem[] = [
    {
      name: '华为终端',
      avatar: $r('app.media.flower'),
      title: '2024,二百万粉阿华继续冲压!!!',
      isFollow: false
    },
    {
      name: '黑马程序员',
      avatar: $r('app.media.flower'),
      title: '领取课程源码+资料,关注黑马程序员公众,回复:领取资源02',
      isFollow: true
    },
    {
      name: '央视新闻',
      avatar: $r('app.media.flower'),
      title: '中央广播电视总台央视新闻官方账号',
      isFollow: false
    },
  ]

  build() {
    List() {
      ForEach(this.playerList, (item: FansItem) => {
        ListItem() {
          Row({ space: 15 }) {
            Image($r('app.media.flower'))
              .width(48)
              .aspectRatio(1)
              .borderRadius(24)
            Column() {
              Text(item.name)
              Text(item.title)
                .fontColor('#999999')
                .maxLines(1)
                .textOverflow({ overflow: TextOverflow.Ellipsis })
            }
            .layoutWeight(1)
            .alignItems(HorizontalAlign.Start)

            if (item.isFollow) {
              Button('已关注')
                .customButton()
                .backgroundColor('#acacac')
            } else {
              Button('回关')
                .customButton()
                .backgroundColor('#ffaa00')
            }
          }
          .width('100%')
          .height(80)
        }
      })
    }
    .padding(15)
    .width('100%')
    .height('100%')
    .margin({ top: 50 })
  }
}

@Extend(Button)
function customButton() {
  .fontSize(12)
  .padding(0)
  .size({ width: 60, height: 30 })
}

这个界面不涉及到动态交互,下一篇我们将会涉及到