在鸿蒙(HarmonyOS)ArkTS开发中,export default struct 是声明自定义组件的标准语法,用于构建UI页面。使用export default的页面默认会被识别成导航的加载页面。以下是关键要点和代码规范:

核心语法结构

export default struct ComponentName {
  // 状态变量或属性声明
  @State isOn: boolean = false 

  // UI构建入口
  build() {
    // 必须返回单个根容器组件
    Column() {
      // 子组件内容
      Text('标题')
        .fontSize(20)
    }
    .width('100%')
  }
}

关键规则

  1. 组件命名

    • 首字母必须大写(如 SettingPage)
    • 需添加 @Component 装饰器(ArkTS特有)
  2. build() 方法

    • 每个组件必须包含 build() 方法
    • 必须返回单个根容器(如 Column/Row/Flex)
  3. 资源引用

    Image($r('app.media.icon')) // 正确资源引用方式
    Text($r('app.string.title')) 
  4. 样式设置

    • 链式调用设置样式:
    Text('内容')
      .fontSize(16)
      .margin({ top: 10 })
      .backgroundColor(Color.White)

完整示例

@Entry
@Component
export default struct Setting {
  build() {
    Column() {
      Text('我的')
        .width('100%')
        .margin({ top: '48vp', bottom: '12vp' })
        .fontWeight(700)
        .fontSize('26fp')
      
      Row() {
        Image($r('app.media.account'))
          .width('48vp')
          .height('48vp')
        Column() {
          Text('李先生').fontSize('20fp')
          Text('2000000@test.cc').fontSize('12fp')
        }
        .margin({ left: '12vp' })
      }
      .alignItems(VerticalAlign.Center)
    }
    .width('100%')
    .height('100%')
  }
}

关键说明

  • @Entry:@Entry装饰的自定义组件将作为UI页面的入口。
  • vp/fp:鸿蒙专用单位(虚拟像素/字体像素)
  • $r('app.media.x'):资源系统安全引用方式
  • 布局容器需显式设置尺寸(如 width('100%'))

此语法结构是鸿蒙ArkTS UI开发的基石,所有自定义组件均需按此规范声明。

Logo

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

更多推荐