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

HarmonyOS
4天前
浏览
收藏 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}分`)
    }
  }
}
分享
微博
QQ
微信
回复
4天前
相关问题
ObserveObjectLink 使用
216浏览 • 1回复 待解决