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

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
Excelsior_abit

如何监听数组内对象属性变化 具体实现方法参考地址: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)
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
如何监听数组对象属性变化
2374浏览 • 1回复 待解决
数组中元素变更如何触发刷新list?
403浏览 • 1回复 待解决
readonly修饰数组无法获取数组元素
2060浏览 • 1回复 待解决