HarmonyOS鸿蒙Next中ArkUI如何监听数组内对象属性变化

HarmonyOS鸿蒙Next中ArkUI如何监听数组内对象属性变化 数组内存储对象示例,需要对对象的属性变化进行监听

5 回复

更多关于HarmonyOS鸿蒙Next中ArkUI如何监听数组内对象属性变化的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


通过@Observed配合@ObjectLink装饰符实现。@Observed用于类,@ObjectLink用于变量。

步骤1:在类上使用@Observed

[@Observed](/user/Observed)
class ClassA {
  public name: string
  public c: number
  public id: number

  constructor(c: number, name: string = 'OK') {
    this.name = name
    this.c = c
  }
}

步骤2:在组件变量使用@ObjectLink

@Component
struct ViewA {
  label: string = 'ViewA1'
  [@ObjectLink](/user/ObjectLink) a: ClassA

  build() {
    Row() {
      Button(`ViewA [${this.label}] this.a.c= ${this.a.c} +1`)
        .onClick(() => {
          this.a.c += 1
        })
    }.margin({ top: 10 })
  }
}

反正都要拆分父子组件,用prop或者Link有什么区别,

在HarmonyOS鸿蒙Next中,ArkUI可以通过@Observed@ObjectLink装饰器来监听数组内对象属性的变化。具体步骤如下:

  1. 定义数据模型类:使用@Observed装饰器标记数据模型类,以便ArkUI能够监听该类的对象属性变化。
@Observed
class Item {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
}
  1. 定义数组属性:在组件中定义一个数组属性,并使用@Observed装饰器标记该数组。
@Observed
class ItemList {
  items: Item[];
  constructor(items: Item[]) {
    this.items = items;
  }
}
  1. 绑定数组属性:在UI组件中使用@ObjectLink装饰器绑定数组属性,以便在UI中动态展示数组内容。
@Component
struct ItemView {
  @ObjectLink item: Item;

  build() {
    Text(this.item.name)
  }
}
  1. 监听数组变化:在UI组件中使用@Observed@ObjectLink装饰器监听数组内对象属性的变化,并在UI中动态更新。
@Component
struct ItemListView {
  @ObjectLink itemList: ItemList;

  build() {
    Column() {
      ForEach(this.itemList.items, (item: Item) => {
        ItemView({ item: item })
      })
    }
  }
}
  1. 更新数组内容:在业务逻辑中更新数组内容时,ArkUI会自动监听并更新UI。
let itemList = new ItemList([new Item("Item1"), new Item("Item2")]);
itemList.items[0].name = "Updated Item1";

通过以上步骤,ArkUI能够监听数组内对象属性的变化,并在UI中动态更新。

在HarmonyOS的ArkUI中,要监听数组内对象属性的变化,可以使用@Observed@ObjectLink装饰器。首先,用@Observed标记包含对象的类;然后,在组件中使用@ObjectLink绑定数组中的对象。当对象属性变化时,ArkUI会自动更新UI。例如:

@Observed
class Item {
  name: string = '';

  constructor(name: string) {
    this.name = name;
  }
}

@Entry
@Component
struct MyComponent {
  @State items: Item[] = [new Item('Item1'), new Item('Item2')];

  build() {
    Column() {
      ForEach(this.items, (item: Item) => {
        Text(item.name)
          .onClick(() => {
            item.name = 'Updated';
          })
      })
    }
  }
}

点击文本时,item.name更新,UI自动刷新。

回到顶部