@Component

标签修饰UI,相当于Android的view,所有的UI组件都要使用@Component标签

@Entry标签

表明当前是一个页面,不是一个视图。多个组件组合时只能有一个@Entry标签,被该标签修饰后页面才会有生命周期

import router from '@ohos.router'
@Entry
@Component
struct Login {
  @State title: string = '登录页面'

  build() {
    Row() {

      Column() {

        Text(this.title).fontSize(20)
          .fontWeight(FontWeight.Bold)
          .textAlign(TextAlign.Center)
          .width('100%').margin({top:10})

        Button() {
          Text('返回')
            .fontSize(18)
            .fontWeight(FontWeight.Bold)
        }.type(ButtonType.Capsule)
        .padding({top:5,bottom:5,left:10,right:10})
        .margin({top:20})
        .onClick(()=>{
          try{
            router.back()
          }catch (err){
            console.error("错误="+err.code +" message="+err.message)
          }
        })
      }
    }.width('100%')
  }

  onPageShow(){
    //页面每次显示时触发
  }

  onPageHide(){
    //页面每次隐藏时触发
  }

  onBackPress(){
    //用户点击返回按钮时触发
  }

  aboutToAppear(){
    //在执行build函数之前执行
  }

  aboutToDisappear(){
    //组件即将销毁时执行
  }
}

@Builder标签

使用该标签的方法会自动构建一个组件

  • 全局方式
@Builder function xxx{}
  • 组件内方式
@Builder xx{}

需要传递参数时采用引用传递 $$

//方法
@Builder function builderFunc($$:{showText:string}){
  Text('全局 builder方法 '+$$.showText)
    .fontSize(18)
    .fontColor("#333333")
}
//调用
builderFunc({showText:'全局猪头'})

@BuilderParam标签

对应@Builder标签,类似于java的接口传递

/**
 * 全局styles样式
 */
@Styles function globalFancy(){
  .width(100)
  .height(150)
  .backgroundColor(Color.Pink)
}

@Builder function builderFunc($$:{showText:string}){
  Text('全局 builder方法 '+$$.showText)
    .fontSize(18)
    .fontColor("#333333")
}

@Component
struct testBuildParam{

  @BuilderParam param:()=>void

  build(){
    Column(){
      this.param()
    }
  }
}


//页面入口
@Entry
@Component
struct StylesPage{

  @State heightNum:number = 100

  @Styles selfFancy(){
    .width(120)
    .height(this.heightNum)
    .backgroundColor(Color.Yellow)
    .onClick(()=>{
      this.heightNum = 180
    })
  }

  @Builder builderSelf(){
    Text("组件内方法")
      .fontSize(15)
      .fontColor("#999999")
      .margin({top:20})
  }

  build(){

    Column({space:10}){
      Text("全局引用styles")
        .globalFancy()
        .fontSize(25)

      Text("组件内的style")
        .selfFancy()
        .fontSize(18)

      this.builderSelf()
      builderFunc({showText:'全局猪头'})

      testBuildParam({param:this.builderSelf})

    }

  }
}