数组对象,应用会根据开发需要,封装自己的数据模型。其中涉及到多层嵌套的情况。

应用会根据开发需要,封装自己的数据模型。其中涉及到多层嵌套的情况。

HarmonyOS
2024-05-23 23:34:22
1317浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
热辣牛奶

@Observed装饰器和@ObjectLink装饰器,观察对象数组中对象属性值的变化,观察数组的UI刷新。

核心代码解释

@Observed 
class type extends Array<Person> { 
} 
  
@Observed 
class Person { 
  name: string 
  age: number 
  changed: boolean 
  
  constructor(name: string, age: number, changed: boolean) { 
    this.name = name 
    this.age = age 
    this.changed = changed 
  } 
} 
  
@Component 
struct ItemView1 { 
  @ObjectLink person1: type 
  build() { 
    Column() { 
      Text(JSON.stringify(this.person1)) 
    } 
  } 
} 
  
@Component 
struct ItemView { 
  @ObjectLink person: Person 
  
  build() { 
    Column(){ 
      Row() { 
        Text(this.person.name).itemText(this.person.changed) 
        Blank() 
        Text(this.person.age.toString()).itemText(this.person.changed) 
      } 
      .width('100%') 
      .height(50) 
      .padding(5) 
      .backgroundColor('#F7F8FA') 
      .onClick(() => { 
        this.person.age++ 
        this.person.changed = true 
      }) 
    } 
  } 
} 
  
@Entry 
@Component 
struct ObjectArrDemo2Page { 
  
  @State per1:Person = new Person('Roes', 12, false); 
  @State persons: Person[] = [this.per1] 
  
  private count: number = 0 
  build() { 
    Column({ space: 10 }) { 
      ItemView1({person1:[this.per1]}) 
  
      List({ space: 5 }) { 
        ForEach(this.persons, (item: Person, index: number) => { 
          ListItem() { 
            ItemView({ person: item }) 
          } 
        }) 
      } 
    } 
    .width('100%') 
    .height('100%') 
    .padding(5) 
  } 
} 
  
@Extend(Text) 
function itemText(changed: boolean) { 
  .fontSize(22) 
  .fontColor(changed ? '#21A3A1' : '#000000') 
}
  • 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.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
分享
微博
QQ
微信
回复
2024-05-24 23:21:19
相关问题
HarmonyOS 数据模型对象赋值问题
867浏览 • 1回复 待解决
如何测试自己开发应用
3302浏览 • 1回复 待解决
HarmonyOS 数组对象数据刷新
858浏览 • 1回复 待解决