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})
    }
  }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章