这是一个工程创建完成的项目:

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

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize($r('app.float.page_text_font_size'))
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
        .onClick(() => {
          this.message = 'Welcome';
        })
    }
    .height('100%')
    .width('100%')
  }
}

        其中,@Component装饰器装饰了struct关键字声明的数据结构Index。Index被@Component装饰后具备组件化的能力,通过实现build方法描述UI。

@Component

         @Entry装饰的@Component将作为UI页面的入口。在单个UI页面中,最多可以使用@Entry装饰一个自定义组件。

@Entry

        界面由RelativeContainer相对布局容器作为根容器,RelativeContainer支持容器内部的子元素设置相对位置关系,适用于界面复杂场景的情况,对多个子组件进行对齐和排列。

RelativeContainer() {
    
        //我是内容部分~~~
        //内容全部写在我这里~~~

    }

         通过Text组件展示一段文本。

Text(this.message)

        文本信息由@State装饰器装饰的状态变量message驱动。

  @State message: string = 'Hello World';

        Text组件定义了组件标识id为HelloWorld,用于唯一指定组件。

 .id('HelloWorld')

        定义字体大小fontSize取值为50;定义文本的字体粗细fontWeight取值为Bold,即字体较粗。

  .fontSize(50)
  .fontWeight(FontWeight.Bold)

         alignRules属性用于指定设置在相对容器中子组件的对齐规则,仅当父容器为RelativeContainer时生效,在这里定义Text组件横向居中和纵向居中。

.alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })

Logo

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

更多推荐