ArkTS/ArkUI实战

十一、鸿蒙ArkTS/ArkUI实战-装饰器@Link

2023-11-21  本文已影响0人  ISwiftUI

@Link装饰的变量可以和父组件的@State变量建立双向数据绑定:

下面的示例是演示Child组件中的count变量是@Prop修饰的,Child2组件中的count变量是@Link修饰的,当点击Child组件的按钮时会发现只有Child组件count数据更新并更新了界面,当点击Child2组件的按钮时会发现所有的count数据都更新并且界面更新了,当点击父组件的按钮也会发现所有的组件中count数据发生了更新并且界面发生更新了

import router from '@ohos.router';
@Entry
@Component
struct Second {
  @State message: string = 'Hello World Second'
  @State num: number = 1

  build() {
    Row() {
      Column() {
        this.TextBuild()
        Child({ count: this.num })
        Child2({ count: $num })
        Button() {
          Text('Back')
            .fontSize(45)
            .fontColor($r('app.color.start_window_background'))
        }
        .type(ButtonType.Capsule)
        .width('60%')
        .height('10%')
        .backgroundColor($r('app.color.button_next_background'))
        .onClick(() => {
          router.back()
        })

        Button() {
          Text(`Num++ ${this.num}`)
            .fontSize(45)
            .fontColor($r('app.color.start_window_background'))
        }
        .type(ButtonType.Capsule)
        .width('60%')
        .height('10%')
        .backgroundColor($r('app.color.button_next_background'))
        .margin({ top: 20 })
        .onClick(() => {
          this.num++
        })
      }
      .width('100%')
    }
    .height('100%')
  }

  @Builder TextBuild(){
    Text(this.message)
      .align(Alignment.Center)
      .fontSize(40)
      .fontWeight(FontWeight.Bold)
  }
}

@Component
struct Child {
  //父组件可以改变子组件,子组件不能改变父组件
  @Prop count: number

  build() {
    Column() {
      Text(`You have ${this.count} Nuggets left`).fontSize(18)
      Button('count - costOfOneAttempt')
        .margin(15)
        .onClick(() => {
          this.count--
        })
    }
  }
}

@Component
struct Child2 {
  //父组件与子组件双向绑定
  @Link count: number

  build() {
    Column() {
      Text(`You have ${this.count} Nuggets left`).fontSize(18)
      Button('count - costOfOneAttempt')
        .margin(15)
        .onClick(() => {
          this.count--
        })
    }
  }
}
上一篇 下一篇

猜你喜欢

热点阅读