ArkTS 父子组件通信

前言

鸿蒙开发中有时候会用到父子间的通信。

代码

一、@Link 装饰器:父子双向同步

@Link 装饰的变量与其父组件中的数据源共享相同的值。

父组件:
import buttonTest from "./buttonTest";

@Entry
@Component
struct Index{

  @State fontSize : number = 50

  build(){
    Column({space: 10}){
      Text("hello")
        .fontSize(this.fontSize);
      Button("big")
        .onClick(() => {
          this.fontSize += 10;
        })
      Button("small")
        .onClick(() => {
          this.fontSize -= 10;
        })
      buttonTest({ text: $fontSize })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
子组件
@Component
export default struct buttonTest{

  @Link text: number

  build(){
    Button(`${this.text}`)
      .onClick(() => {
        this.text = 100
      })
  }
}
二、@Provide 装饰器和 @Consume 装饰器:与后代组件双向同步

@Provide@Consume,应用于与后代组件的双向数据同步,应用于状态数据在多个层级之间传递的场景。不同于 @Link 的父子组件之间通过命名参数机制传递,@Provide@Consume 摆脱参数传递机制的束缚,实现跨层级传递。

@Provide 装饰的变量是在祖先组件中,可以理解为被“提供”给后代的状态变量。
@Consume 装饰的变量是在后代组件中,去“消费(绑定)”祖先组件提供的变量。

父组件:
import buttonTest from "./buttonTest";

@Entry
@Component
struct Index{

  @Provide fontSize : number = 50

  build(){
    Column({space: 10}){
      Text("hello")
        .fontSize(this.fontSize);
      Button("big")
        .onClick(() => {
          this.fontSize += 10;
        })
      Button("small")
        .onClick(() => {
          this.fontSize -= 10;
        })
      buttonTest()
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Center)
  }
}
子组件:
@Component
export default struct buttonTest{

  @Consume fontSize: number

  build(){
    Button(`${this.fontSize}`)
      .onClick(() => {
        this.fontSize = 100;
      })
  }
}

你可能感兴趣的:(ArkTS,鸿蒙,typescript)