HarmonyOS @ObjectLink 装饰器装饰的变量成员子组件中无法感知更新

代码如下

@Entry 
@Component 
struct Index { 
  @State uiState: ObservedA = new ObservedA() 
 
  build() { 
    Row() { 
      Column() { 
        ComponentA({ 
          uiState: this.uiState 
        }) 
 
        Button('addCount') 
          .onClick(() => { 
            this.uiState.ob.b++ 
          }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
  } 
} 
 
@Component 
struct ComponentA { 
  @ObjectLink uiState: ObservedA 
 
  build() { 
    ComponentB({ 
      uiState: this.uiState.ob 
    }) 
  } 
} 
 
@Component 
struct ComponentB { 
  @ObjectLink uiState: ObservedB 
 
  build() { 
    ComponentC({ 
      content: this.uiState.b 
    }) 
  } 
} 
 
@Component 
struct ComponentC { 
  @State content: number = 0 
 
  build() { 
    Text(`${this.content}`) 
  } 
} 
 
@Observed 
class ObservedA { 
  a: number = 0 
  ob: ObservedB = new ObservedB() 
} 
 
@Observed 
class ObservedB { 
  b: number = 0 
}

点击按钮更新字段 b,组件 C 中无法感知到更新,如何处理实现该功能

HarmonyOS
2024-08-04 14:35:28
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
e_leaner

参考如下demo:

@Entry 
@Component 
struct Index { 
  @State uiState: ObservedA = new ObservedA() 
 
  build() { 
    Row() { 
      Column() { 
        ComponentA({ 
          uiState: this.uiState 
        }) 
        Button('addCount') 
          .onClick(() => { 
          this.uiState.ob.b++ 
        }) 
      } 
      .width('100%') 
    } 
    .height('100%') 
 
  } 
} 
 
 
@Component 
struct ComponentA { 
  @ObjectLink uiState: ObservedA 
 
 
  build() { 
    ComponentB({ 
      uiState: this.uiState.ob 
    }) 
  } 
} 
 
 
@Component 
struct ComponentB { 
  @ObjectLink uiState: ObservedB 
 
 
  build() { 
    // ComponentC({ 
    //   content: this.uiState.b 
    // }) 
    Text(this.uiState.b.toString()) 
  } 
} 
 
 
// @Component 
// struct ComponentC { 
//   @State content: number = 0 
// 
// 
//   build() { 
//     Text(this.content.toString()) 
//   } 
// } 
 
 
@Observed 
class ObservedA { 
  a: number = 0 
  ob: ObservedB = new ObservedB() 
} 
 
 
@Observed 
class ObservedB { 
  b: number = 0 
}

主要原因是Component C中的@State content: number = 0中@State无法实现父子传值,需要使用@Prop或@Link支持父子间传值的装饰器才可实现,Observed使用可参考如下链接

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/arkts-observed-and-objectlink-0000001774279618-V5

分享
微博
QQ
微信
回复
2024-08-05 12:09:12
相关问题
装饰 @Styles 和 @Extend
325浏览 • 1回复 待解决
HarmonyOS 装饰不刷新问题
90浏览 • 1回复 待解决
应用卡片内部组件能使用装饰吗?
244浏览 • 1回复 待解决
Aspect工具装饰使用示例
1961浏览 • 2回复 待解决
@Track装饰有什么作用?
661浏览 • 1回复 待解决