ArkTS Prop組件使用案例

 

 

/**
 * Prop組件使用案例
 */
@Component
struct MyChild {

  @Prop
  age:number // 狀態變量

  private increase:number = 1

  build() {
    Column() {
      if (this.age >= 18) {
        Text(`子組件中的age已經成年了:${this.age}`)
          .height(80)
      } else {
        Text(`子組件未成年:${this.age}`).height(80)
      }

      Button('--修改子組件age')
        .onClick(() => {
          this.age -= this.increase
        })
        .height(80)
        .width(250)
        .margin(5)
    }
  }
}


@Entry
@Component
struct MyParent {
  @State
  init_age:number = 16

  build(){
    Column() {
      Text(`父組件中的初始age:${this.init_age}`)
        .height(80)
      Button('修改父組件的init_age')
        .onClick(()=>{
          this.init_age += 1
        })
        .height(80)
        .width(250)
        .margin(5)

      Divider()

      MyChild({age:this.init_age, increase: 2})

      Divider()
      Divider()
      // MyChild({increase: 3})
    }
  }
}

 

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