ArkTs state prop link的区别和使用方法

216 阅读2分钟

@State 允许装饰的变量类型有 string 、 number 、 boolean 、 object 、 class 和enum 类型,以及这些类型的数组。

@Prop 允许装饰的变量类型有 string 、 number 、 boolean 、 enum ,注意不⽀持 class 、 object 和数组。

@Link 允许装饰的变量类型有 string 、 number 、 boolean 、 object 、 class 和enum 类型,以及这些类型的数组。

@Provide 和@Consume 允许装饰的变量类型有 string 、 number 、 boolean 、 object 、 class 和enum 类型,以及这些类型的数组。

以上这些状态属性: 当装饰的数据类型为boolean、string、number类型时,可以观察到数值的变化 当装饰的数据类型为class或者object时,可以观察到变量⾃身赋值的变化,和其属性赋值的 变化。需要注意的是,若某个属性也为 class 或者 object,则嵌套属性的变化是观察不到

的。 当装饰的数据类型为数组时,可以可以观察到数组本身赋值的变化,和其元素的添加、删除 及更新的变化,若元素类型为 class 或者 object 时,元素属性的变化,是观察不到的。

@Entry
@Component
struct StatePag {
  @State count: number = 1; //State 装饰的变量必须进⾏本地初始化

  build() {
    Column({ space: 50 }) {

      Row({ space: 10 }) {
        Text('@State 父组件').textCountStyle()
        //计数器
        Counter() {
          Text(this.count.toString()).textCountStyle()
        }
        .onInc(() => this.count++) //加法++
        .onDec(() => this.count--) //减法--

      }
      .width('100%')
      .backgroundColor("#CCE3CB")
      .padding(10)
      .borderRadius(20)
      .justifyContent(FlexAlign.Center)

      //子组件
      StatePropChild({ count: this.count })
      //子组件 Link必须使⽤ $变量名 的⽅式传参,以表示传递的是变量的引⽤。
      StateLinkChild({ count: $count })

    }
    .height('100%')
    .width('100%')
    .justifyContent(FlexAlign.Center)
    .backgroundColor(Color.White)
    .padding(10)

  }
}

@Component//父组件->子组件 子组件->父组件
struct StateLinkChild {

  //装饰的变量不允许本地初始化,只能由⽗组件通过传参进⾏初始化,并且⽗组
  // 件必须使⽤ $变量名 的⽅式传参,以表示传递的是变量的引⽤。
  @Link count: number;

  build() {
    Column({ space: 10 }) {
      //子组件标题
      Text('子组件').textCountStyle()
      //子组件计数器
      Row({ space: 10 }) {
        Text('@Link').textCountStyle()
        Counter() {
          Text(this.count.toString()).textCountStyle()
        }
        .onInc(() => this.count++)
        .onDec(() => this.count--)
      }
    }
    .containerPropStyle('#CCE3CB')
  }
}

@Component //父组件->子组件
struct StatePropChild {

  @Prop count: number ; //@Prop装饰的变量不允许本地初始化,只能通过⽗组件向⼦组件传参进⾏初始化

  build() {
    Column({ space: 10 }) {
      //子组件标题
      Text('子组件').textCountStyle()

      //子组件计数器
      Row({ space: 10 }) {
        Text('@Prop').textCountStyle()
        Counter() {
          Text(this.count.toString()).textCountStyle()
        }
        .onInc(() => this.count++)
        .onDec(() => this.count--)
      }
    }
    .containerPropStyle("#CCE3CB")
  }
}

@Extend(Text) function textCountStyle() {
  .fontSize(25)
  .fontWeight(FontWeight.Bold)
}

@Extend(Column) function containerPropStyle(color: ResourceColor) {
  .width('100%')
  .backgroundColor(color)
  .padding(10)
  .borderRadius(20)
}