ArkTS父子组件双向绑定案例

 

/**
 * 父子组件双向互绑定
 */
// 自定义按钮的信息类型
class ButtonState  {

  value:string
  width:number

  constructor(value:string,width:number) {
    this.value = value
    this.width = width
  }
}

@Component
struct MyChildGreenButton {
  // 拥有绿色按钮的组件,Link装饰器实现双向同步
  @Link
  buttonState: ButtonState
  build(){
    Button(`${this.buttonState.value}`)
      .width(this.buttonState.width)
      .height(150)
      .backgroundColor(Color.Green)
      .onClick(()=>{
        if (this.buttonState.width < 700) {
          this.buttonState.width += 100
        }
         else {
           this.buttonState = new ButtonState('绿色按钮', 100)
         }
      })
  }
}

@Component
struct MyChildRedButton {
  // 拥有红色按钮的组件,Link装饰器实现双向同步
  @Link
  value : string
  @Link
  buttonWidth:number

  build(){
    Button(`${this.value}`)
      .width(this.buttonWidth)
      .height(150)
      .backgroundColor(Color.Red)
      .onClick(()=>{
        this.buttonWidth += 50
      })
  }
}

@Entry
@Component
struct MyParent {
  @State parentGreenButton:ButtonState = new ButtonState('壹号子组件',300)
  @State parentRedValue: string = '二号子组件'
  @State parentRedWidth: number = 200 // h红按钮的宽度

  build(){
    Column() {
      // 父组件中调整按钮的宽度
      Button(`父组件中修改绿色按钮的宽度:${this.parentGreenButton.width}`)
        .onClick(()=>{
          this.parentGreenButton.width = this.parentGreenButton.width < 700 ? this.parentGreenButton.width + 100 : 100
        })

      Button(`父组件中修改红色按钮的宽度:${this.parentRedWidth}`)
        .onClick(()=>{
          this.parentRedWidth = this.parentRedWidth < 700 ? this.parentRedWidth + 100 : 100
        })

      Divider()
      MyChildGreenButton({buttonState: $parentGreenButton})
      MyChildRedButton({value:$parentRedValue, buttonWidth: $parentRedWidth})
    }
  }
}

 

 

来源B站公开视频:
华为大佬最新鸿蒙HarmonyOS4.0(鸿蒙4)开发应用从入门到实战视频教程

posted @ 2024-01-14 21:17  宝山方圆  阅读(65)  评论(0编辑  收藏  举报