鸿蒙页面示例

电子说

1.2w人已加入

描述

@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})

    }

  }
}


审核编辑 黄宇

HTML 1800 字数 121 段落

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分