自定义构建函数可以定义在UI内部,也可以定义在UI外部,两者都可以传递参数,传参的方式有两种,1、按值传递、2、按引用传递

一、定义在UI外部

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Row({space: 10}) {
        Text('测试')
          .width(50)
          .backgroundColor(Color.Pink)
          .aspectRatio(0.5)
          .onClick(() => {
            this.message += '~'
          })
          //定义在外部直接全局拿函数调用
        testFn(this.message)
        testFn1({msg: this.message})
      }
      .width('100%')
    }
    .height('100%')
  }
}
//此方法为【按值传递】,UI内部修改参数不会同步到此方法内
@Builder function testFn(msg: string) {
    Row(){
      Text(`msg ==== ${msg}`)
    }
}
//此方法为【按引用传递】,UI内部修改参数会同步到此方法内
@Builder function testFn1 ($$: {msg: string}) {
  Row(){
    Text(`msg ==== ${$$.msg}`)
  }
}

二、定义在UI内部

@Entry
@Component
struct Index {
  @State message: string = 'Hello World'

  build() {
    Row() {
      Row({ space: 10 }) {
        Text()
          .width(50)
          .backgroundColor(Color.Pink)
          .aspectRatio(0.5)
          .onClick(() => {
            this.message += '~'
          })
          //定义在内部,需要通过this拿到函数调用
        this.testFn(this.message)
        this.testFn1({ msg: this.message })
      }
      .width('100%')
    }
    .height('100%')
  }
//此方法为【按值传递】,UI内部修改参数不会同步到此方法内
  @Builder testFn(msg: string) {
    Row() {
      Text(`msg ==== ${msg}`)
    }
  }
//此方法为【按引用传递】,UI内部修改参数会同步到此方法内
  @Builder testFn1($$: { msg: string }) {
    Row() {
      Text(`msg ==== ${$$.msg}`)
    }
  }
}
Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐