HarmonyOS 跨har使用@Provider/@Consumer,无法被@Monitor观察的问题?

HAR中有组件Parent,如下实现

@ComponentV2
export struct Parent {

  @Provider() helloworld: string = ''

  @BuilderParam child: () => void

  build() {

    Column() {
      this.child()
    }
  }

  aboutToAppear(): void {

    setTimeout(() => {

      this.helloworld = '!!!!!!!!!!!!'
    }, 5000)
  }
}

//entry中有组件Child,如下实现

@ComponentV2
export struct Child {

  @Consumer() helloworld: string = ''

  build() {
    Button('anniu')
  }

  @Monitor('helloworld')
  onHelloworld(monitor: IMonitor) {

    const a = monitor.dirty
    console.log(`${a}`)
  }
}

//Parent和Child组合使用

build() {
  Parent() {
    Child()
  }
}

5秒后,onHelloworld 方法并没有收到响应,但把Child与Parent一同放到HAR,并组合使用,onHelloworld 却收到响应

为什么会出现这样的情况?

阅读 527
1 个回答

这里使用尾随闭包方式跨har包调用,里面通用属性会失效,导致更新数据无法刷新; 可以使用自定义构建函数(@Builder装饰的方法)传参;

例如 entry中的页面可以试下下面调用方法: Parent({ child: ChildComponent });

@ComponentV2
export struct Child {
  @Consumer() helloworld: string = ''

  build() {
    Button('anniu')
      .onClick(() => {
        this.helloworld = 'sssssssss'
      })
  }

  @Monitor('helloworld')
  onHelloworld(monitor: IMonitor) {

    const a = monitor.dirty
    console.log('monitor.change' + JSON.stringify(monitor))
  }
}

@Builder
function ChildComponent() {
  Child()
}

@Entry
@ComponentV2
struct Index {
  build() {
    Column() {
      Parent({ child: ChildComponent })
    }
    .height('100%')
    .width('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进