回复
     ETS装饰器学习之Preview、Builder 原创
droidzxy
 发布于 2022-10-27 13:49
 浏览
 0收藏
在学习声明式UI框架ArkUI的过程中,会遇到装饰器的概念,不管是简单的示例页面还是复杂的大程序,都离不开装饰器的使用,为了帮助自己对装饰器有一个基本的了解,并能够熟练的使用,所以专门针对ets装饰器系统的学习了一下,并整理成简单的笔记,以便健忘的我随时回来复习一下。
 
本文主要介绍Preview和Builder,Preview装饰的自定义组件可以在预览器上进行预览,Builder用来在struct内部定义一个方法,该方法可以被build函数多次调用,常用在把一类UI元素的布局组成一个集合,然后在需要的地方直接调用,就像函数调用子函数。
 
@Preview
装饰struct,用@Preview装饰的自定义组件可以在DevEco Studio的预览器上进行预览,加载页面时,将创建并呈现@Preview装饰的自定义组件。
主要特征:
- 组件预览功能要求compileSdkVersion为8或以上。
 - 组件预览支持实时预览,不支持动态图和动态预览。
 - 单个页面文件最多支持10个@Preview装饰的自定义组件。
 
在组件预览模式中,默认的是Page Mode(蓝色显示),

预览组件需要切换到Component Mode(蓝色显示),

示例代码:
@Entry
@Component
struct Index {
  build() {
    Column() {
      ComponentA()
      ComponentB()
    }
    .justifyContent(FlexAlign.Center)
    .width('100%')
    .height('100%')
  }
}
@Preview
@Component
struct ComponentA {
  build() {
    Row() {
      Column() {
        Text("This is ComponentA")
          .fontSize(30)
          .fontColor(Color.Red)
      }
      .width('100%')
    }
    .height(50)
  }
}
@Preview
@Component
struct ComponentB {
  build() {
    Row() {
      Column() {
        Text("This is ComponentB")
          .fontSize(30)
          .fontColor(Color.White)
        Button("Click")
          .margin({top: 20})
          .width(80)
      }
      .width('100%')
      .backgroundColor(Color.Gray)
      .padding(10)
    }
    .height(150)
    .width('90%')
  }
}
页面预览:

组件预览:

在页面预览中,点击按钮可以看到点击的效果,但在组件预览中点击按钮没有动态效果。


@Builder
@Builder装饰器定义了一个如何渲染自定义组件的方法,语法和作用和build函数一致。
通过@Builder装饰器可以构建自定义方法,抽象出相同的UI结构声明,这样在显示多个相同的布局内容的情况下,就可以用@Builder先抽象化,然后在build函数中多次调用,不仅可以减少大量重复的代码,而且方便管理,减少出错。
在struct结构体里,可以定义一个或者多个@Builder修饰的方法,但Component的build方法只有一个。
示例代码:
@Entry
@Component
struct Index {
  build() {
    Column() {
      BuilderExample()
    }
    .alignItems(HorizontalAlign.Center)
  }
}
@Component
struct BuilderExample {
  @Builder RowGroup(name:string, value:string) {
    Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Text(name)
        .fontSize(20)
        .fontWeight(FontWeight.Bold)
        .width(150)
        .margin({left:20})
      Text(value)
        .fontSize(20)
        .layoutWeight(1)
    }
    .width('100%')
    .height(50)
    .padding(10)
    .backgroundColor(0xeeeeee)
    .margin(2)
  }
  build() {
    Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Start, alignItems: ItemAlign.Start }) {
      this.RowGroup('Mary', '32')
      this.RowGroup('Bob', '28')
      this.RowGroup('Susan', '37')
    }
    .height('100%')
  }
}
效果预览:

Builder装饰器,适合页面布局中,同类代码反复调用的情况。
©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
  标签 
  已于2022-11-7 08:44:51修改
 
        赞
        1
 
        收藏 
      
 回复
  相关推荐
 



















