#鸿蒙通关秘籍#使用@Observed和@ObjectLink处理多层嵌套对象变化

HarmonyOS
2024-11-26 16:00:04
792浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
NEXT 天然编程

通过@Observed和@ObjectLink处理多层嵌套对象的属性变化,使其能响应UI更新:

@Observed
class Student {
  name: string
  sex: string
  score: ScoreData

  constructor(name: string, sex: string, score: ScoreData) {
    this.name = name
    this.sex = sex
    this.score = score
  }
}

@Observed
class ScoreData {
  math: number
  chinese: number
  english: number

  constructor(math: number, chinese: number, english: number) {
    this.math = math
    this.chinese = chinese
    this.english = english
  }
}

@Entry
@Component
struct Demo {
  @State student: Student = new Student("王明", "男", new ScoreData(80, 90, 75))

  build() {
    Column({ space: 10 }) {
      Text(`姓名:${this.student.name}`)
      Text(`性别:${this.student.sex}`)
      ScoreView({
        data: this.student.score
      })

      Button('改变性别').onClick(() => {
        this.student.sex = '女'
      })

      Button('改变数学成绩').onClick(() => {
        this.student.score.math = 10
      })

      Button('改变语文成绩').onClick(() => {
        this.student.score.chinese--
      })

    }.width('100%').padding(20).alignItems(HorizontalAlign.Start)
  }
}

@Component
struct ScoreView {
  @ObjectLink data: ScoreData

  build() {
    Column() {
      Text(`数学成绩:${this.data.math}`)
      Text(`语文成绩:${this.data.chinese}`)
      Text(`英语成绩:${this.data.english}`)
    }
  }
}
  • 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.
  • 67.
分享
微博
QQ
微信
回复
2024-11-26 16:55:09
相关问题
ObserveObjectLink 使用
962浏览 • 1回复 待解决