HarmonyOS 如何监听数组对象中元素属性的变化?

如题:HarmonyOS 如何监听数组对象中元素属性的变化?

阅读 555
1 个回答

如何监听数组内对象属性变化 具体实现方法参考地址:https://developer.huawei.com/consumer/cn/doc/harmonyos-faqs-V5/faqs-arkui-213-V5

参考示例:

@Observed
export class SoundBean {
  fName: string = '';
  isPlaying: boolean = false;
  testClass: TestClass = new TestClass();
  array: TestClass[] = [new TestClass(),new TestClass()]
}
@Observed
export class TestClass {
  name: string = "123";
  six: string = "456";
}
@Entry
@Component
struct Index1 {
  scroller:Scroller = new Scroller()
  @State sounds:Array<SoundBean> = new Array()
  aboutToAppear(): void {
    for (let i = 0; i < 5; i++) {
      let obj:SoundBean = new SoundBean()
      obj.fName= `${i}`
      this.sounds.push(obj)
    }
  }
  @Builder
  getListView() {
    List({ scroller: this.scroller }) {
      ForEach(this.sounds, (soundBean: SoundBean, index: number) => {
        ListItem() {
          AlbumItemView({ soundBean: soundBean })
        }.onClick(() => {
          for (let i = 0; i < this.sounds.length; i++) {
            if (i === index) {
              this.sounds[i].isPlaying = true
              this.sounds[i].fName = 'aaaaa'
              this.sounds[i].testClass.name = "哈哈哈哈"
              this.sounds[i].array[0].six = "男"
            } else {
              this.sounds[i].isPlaying = false
            }
          }
        })
      })
    }
    .width('100%')
    .height('100%')
    .nestedScroll({
      scrollForward: NestedScrollMode.PARENT_FIRST,
      scrollBackward: NestedScrollMode.SELF_FIRST
    })
    .divider({
      strokeWidth: 0.5,
      startMargin: 50,
      endMargin: 0,
      color: '#e5e5e5'
    })
    .edgeEffect(EdgeEffect.None)
    .backgroundColor(Color.White)
  }
  build() {
    Column(){
      this.getListView()
    }
  }
}
@Component
export struct AlbumItemView {
  @ObjectLink soundBean: SoundBean
  build() {
    Row() {
      Row() {
        Column() {
          Text(this.soundBean.testClass.name)
            .fontSize(14).fontColor(this.soundBean.isPlaying ? Color.Green : "#282828")
            .margin({ top: 4 })
        }
        .justifyContent(FlexAlign.Center)
        .alignItems(HorizontalAlign.Start)
        .width(310)
        .height("100%")
        Text(this.soundBean.array[0].six)
          .fontSize(14).fontColor(this.soundBean.isPlaying ? Color.Green : "#282828")
      }.width(330)
      .justifyContent(FlexAlign.SpaceBetween)
    }
    .width("100%")
    .padding({ left: 15, right: 15 })
    .height(58)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进