鸿蒙~@Provide装饰的变量与任何后代组件共享状态数据,通过

2024-01-09  本文已影响0人  胡修波

@Provide装饰的变量可以与任何后代组件共享状态数据,其后代组件使用@Consume创建双向同步,详情见@Provide和@Consume

因此,@Provide-@Consume模式比使用@State-@Link-@Link从父组件将更改传递到孙子组件更方便。@Provide-@Consume适合在单个页面UI组件树中共享状态数据。

使用@Provide-@Consume模式时,@Consume和其祖先组件中的@Provide通过绑定相同的key连接,而不是在组件的构造函数中通过参数来进行传递。

以下示例通过@Provide-@Consume模式,将更改从父组件传递到孙子组件。

@Component
struct LinkLinkChild {
  @Consume @Watch("testNumChange") testNum: number = 0;

  testNumChange(propName: string): void {
    console.log(`LinkLinkChild: testNum value ${this.testNum}`);
  }

  build() {
    Text(`LinkLinkChild: ${this.testNum}`)
  }
}

@Component
struct PropLinkChild {
  @Prop @Watch("testNumChange") testNumGrand: number = 0;

  testNumChange(propName: string): void {
    console.log(`PropLinkChild: testNumGrand value ${this.testNumGrand}`);
  }

  build() {
    Text(`PropLinkChild: ${this.testNumGrand}`)
      .height(70)
      .backgroundColor(Color.Red)
      .onClick(() => {
        this.testNumGrand += 1;
      })
  }
}

@Component
struct Sibling {
  @Consume @Watch("testNumChange") testNum: number;

  testNumChange(propName: string): void {
    console.log(`Sibling: testNumChange value ${this.testNum}`);
  }

  build() {
    Text(`Sibling: ${this.testNum}`)
  }
}

@Component
struct LinkChild {
  @Consume @Watch("testNumChange") testNum: number;

  testNumChange(propName: string): void {
    console.log(`LinkChild: testNumChange value ${this.testNum}`);
  }

  build() {
    Column() {
      Button('incr testNum')
        .onClick(() => {
          console.log(`LinkChild: before value change value ${this.testNum}`);
          this.testNum = this.testNum + 1
          console.log(`LinkChild: after value change value ${this.testNum}`);
        })
      Text(`LinkChild: ${this.testNum}`)
      LinkLinkChild({ /* empty */ })
      PropLinkChild({ testNumGrand: this.testNum })
    }
    .height(200).width(200)
  }
}

@Entry
@Component
struct Parent {
  @Provide @Watch("testNumChange1") testNum: number = 1;

  testNumChange1(propName: string): void {
    console.log(`Parent: testNumChange value ${this.testNum}`)
  }

  build() {
    Column() {
      LinkChild({ /* empty */ })
      Sibling({ /* empty */ })
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读