鸿蒙Next状态管理装饰器V2 @Param@Once@Event

2025-06-27 22:38:27
116次阅读
0个评论

本文补充记录一下V2装饰器 @Param 组件外部输入 @Once初始化同步一次 @Event 规范组件回调 param_once.gif

@Param表示组件从外部传入的状态,使得父子组件之间的数据能够进行同步:

  • @Param装饰的变量支持本地初始化,但是不允许在组件内部直接修改变量本身。
  • 被@Param装饰的变量能够在初始化自定义组件时从外部传入,当数据源也是状态变量时,数据源的修改会同步给@Param。
  • @Param可以接受任意类型的数据源,包括普通变量、状态变量、常量、函数返回值等。
  • @Param装饰的变量变化时,会刷新该变量关联的组件。
  • @Param支持观测number、boolean、string、Object、class等基本类型以及Array、Set、Map、Date等内嵌类型。
  • 对于复杂类型如类对象,@Param会接受数据源的引用。在组件内可以修改类对象中的属性,该修改会同步到数据源。
  • @Param的观测能力仅限于被装饰的变量本身。当装饰简单类型时,对变量的整体改变能够观测到;当装饰对象类型时,仅能观测对象整体的改变;当装饰数组类型时,能观测到数组整体以及数组元素项的改变;当装饰Array、Set、Map、Date等内嵌类型时,可以观测到通过API调用带来的变化。
  • @Param支持null、undefined以及联合类型。
@Entry
@ComponentV2
struct test3{
  @Local message:string='Hello World'
  @Local once_message:string='Hello World'
  build() {
    Column({space:20}){
      Text('父布局:'+this.message).fontSize(20).fontColor(Color.Red)
      Text('父布局:'+this.once_message).fontSize(20).fontColor(Color.Red)
      child1({childMsg:this.message,childOnceMsg:this.once_message})
      Button('刷新').onClick(()=>{
        this.message='Hello HarmonyOS '+Math.floor(Math.random() * 11)
        this.once_message='Hello HarmonyOS '+Math.floor(Math.random() * 11)
      })
    }.width('100%')
    .height('100%')
  }
}
@ComponentV2
struct child1{
  @Require  @Param childMsg:string
  @Require  @Param childOnceMsg:string
  build() {
    child2({childMsg:this.childMsg,childOnceMsg:this.childOnceMsg})
  }
}
@ComponentV2
struct child2{
  @Require  @Param childMsg:string
  @Require  @Param @Once childOnceMsg:string
  build() {
    Column(){
      Text('子布局:'+this.childMsg).fontSize(20)
        .onClick(()=>{
          //Cannot assign to 'childMsg' because it is a read-only property
          // this.childMsg=''
        })
      Text('子布局:'+this.childOnceMsg).fontSize(20)
    }
  }
}

@Once装饰器仅在变量初始化时接受外部传入值进行初始化,当后续数据源更改时,不会将修改同步给子组件: @Once必须搭配@Param使用,单独使用或搭配其他装饰器使用都是不允许的。 @Once不影响@Param的观测能力,仅针对数据源的变化做拦截。 @Once与@Param装饰变量的先后顺序不影响实际功能。 @Once与@Param搭配使用时,可以在本地修改@Param变量的值。 event.gif **@Event**的使用方法类似于Java中的接口回调

@Entry
@ComponentV2
struct test4{
  @Local message:string='Hello World'
  build() {
    Column({space:20}){
      Text('父布局:'+this.message).fontSize(20).fontColor(Color.Red)
      child1({childMsg:this.message,changeMessage:(ms:string)=>{
        this.message = ms;
      }})
      Button('刷新').onClick(()=>{
        this.message='Hello HarmonyOS '+Math.floor(Math.random() * 11)
      })
    }.width('100%')
    .height('100%')
  }
}
@ComponentV2
struct child1{
  @Require  @Param childMsg:string
  @Event changeMessage: (val: string) => void;
  build() {
    Text('子布局:'+this.childMsg).fontSize(20)
      .onClick(()=>{
        this.changeMessage('子组件修改返回')
      })
  }
}

@Event用于装饰组件对外输出的方法: @Event装饰的回调方法中参数以及返回值由开发者决定。 @Event装饰非回调类型的变量不会生效。当@Event没有初始化时,会自动生成一个空的函数作为默认回调。 当@Event未被外部初始化,但本地有默认值时,会使用本地默认的函数进行处理。

收藏00

登录 后评论。没有帐号? 注册 一个。