在HarmonyOS NEXT开发中@Provider与@Consume的数据交互方式?

在HarmonyOS NEXT开发中@Provider与@Consume的数据交互方式?这个只能单向传递,也就是说只允许一个祖先组件来完成变量的更新,孙子组件只能读取不能更改
如果我的子孙组件想要改变该数据变量,请问有什么好的办法没?逐层传递回祖先再改变太繁杂了

阅读 505
1 个回答

@Provide装饰器和@Consume装饰器,可以实现与后代组件双向同步。不需要逐层传递回祖先。参考链接:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides...

@Component 
struct CompD { 
  // @Consume装饰的变量通过相同的属性名绑定其祖先组件CompA内的@Provide装饰的变量 
  @Consume reviewVotes: number; 
 
  build() { 
    Column() { 
      Text(`reviewVotes(${this.reviewVotes})`) 
      Button(`reviewVotes(${this.reviewVotes}), give +1`) 
        .onClick(() => this.reviewVotes += 1) 
    } 
    .width('50%') 
  } 
} 
 
@Component 
struct CompC { 
  build() { 
    Row({ space: 5 }) { 
      CompD() 
      CompD() 
    } 
  } 
} 
 
@Component 
struct CompB { 
  build() { 
    CompC() 
  } 
} 
 
@Entry 
@Component 
struct CompA { 
  // @Provide装饰的变量reviewVotes由入口组件CompA提供其后代组件 
  @Provide reviewVotes: number = 0; 
 
  build() { 
    Column() { 
      Button(`reviewVotes(${this.reviewVotes}), give +1`) 
        .onClick(() => this.reviewVotes += 1) 
      CompB() 
    } 
  } 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进