HarmonyOS ArkTS的基本语法、状态管理和渲染控制的场景

20 阅读1分钟

ArkTS的基本语法

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

  build() {
    Row() {
      Column() {
        Text('item 1')
        Divider()
        Text('item 2')
        Text('test')
          .fontSize(12)
        Button(`Hello ${this.myText}`)
          .onClick(() => {
            this.myText = ' ArkUI';
          })
        
      }
      .width('100%')
    }
    .height('100%')
  }
}

自定义组件的基本用法

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

  build() {
    Row() {
      Column() {
        Text('item 1')
        Divider()
        Text('item 2')
        Text('test')
          .fontSize(12)
        Button(`Hello ${this.myText}`)
          .onClick(() => {
            this.myText = ' ArkUI';
          })
        HelloComponent({hellomessage :"你好"});
      }
      .width('100%')
    }
    .height('100%')
  }
}


@Component
struct HelloComponent {
  @State hellomessage:string = 'Hello World';
  build() {
    Row() {
      Text(this.hellomessage)
        .onClick(() => {
          this.hellomessage = 'hello arkui';
        })
    }
  }
}

自定义组件的基本结构

  • struct:自定义组件基于struct实现,struct + 自定义组件名 + {...}的组合构成自定义组件,不能有继承关系。对于struct的实例化,可以省略new。

@Component:@Component装饰器仅能装饰struct关键字声明的数据结构。struct被@Component装饰后具备组件化的能力,需要实现build方法描述UI,一个struct只能被一个@Component装饰。

build()函数:build()函数用于定义自定义组件的声明式UI描述,自定义组件必须定义build()函数。

@Entry:@Entry装饰的自定义组件将作为UI页面的入口。在单个UI页面中,最多可以使用@Entry装饰一个自定义组件。@Entry可以接受一个可选的LocalStorage的参数。