Skip to content

ArkTS 语法

ArkTS 是 HarmonyOS 应用开发的主力语言,它在 TypeScript 的基础上扩展了声明式 UI、状态管理等能力。

基础语法

变量声明

typescript
// 使用 let 声明可变变量
let count: number = 0

// 使用 const 声明常量
const PI: number = 3.14159

// 类型推断
let message = 'Hello' // 推断为 string 类型

基本类型

typescript
// 数字
let age: number = 25
let price: number = 99.99

// 字符串
let name: string = 'HarmonyOS'
let greeting: string = `Hello, ${name}!`

// 布尔值
let isActive: boolean = true

// 数组
let numbers: number[] = [1, 2, 3]
let names: Array<string> = ['Alice', 'Bob']

// 元组
let tuple: [string, number] = ['age', 25]

// 枚举
enum Color {
  Red,
  Green,
  Blue
}
let color: Color = Color.Red

函数

typescript
// 函数声明
function add(a: number, b: number): number {
  return a + b
}

// 箭头函数
const multiply = (a: number, b: number): number => {
  return a * b
}

// 可选参数
function greet(name: string, age?: number): string {
  if (age) {
    return `Hello ${name}, ${age} years old`
  }
  return `Hello ${name}`
}

// 默认参数
function createUser(name: string, role: string = 'user'): void {
  console.log(`${name} is a ${role}`)
}

接口

typescript
// 定义接口
interface User {
  id: number
  name: string
  email?: string // 可选属性
  readonly createdAt: Date // 只读属性
}

// 使用接口
const user: User = {
  id: 1,
  name: 'Alice',
  createdAt: new Date()
}

typescript
class Person {
  // 属性
  private name: string
  public age: number
  
  // 构造函数
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  
  // 方法
  introduce(): string {
    return `My name is ${this.name}, ${this.age} years old`
  }
  
  // getter
  get displayName(): string {
    return this.name.toUpperCase()
  }
  
  // setter
  set displayName(value: string) {
    this.name = value
  }
}

// 继承
class Student extends Person {
  private grade: number
  
  constructor(name: string, age: number, grade: number) {
    super(name, age)
    this.grade = grade
  }
  
  study(): void {
    console.log(`${this.grade}th grade student is studying`)
  }
}

装饰器

装饰器是 ArkTS 的核心特性,用于增强类和组件的功能。

组件装饰器

typescript
// @Component: 定义自定义组件
@Component
struct MyComponent {
  build() {
    Text('Custom Component')
  }
}

// @Entry: 标记入口组件
@Entry
@Component
struct Index {
  build() {
    Column() {
      MyComponent()
    }
  }
}

// @Preview: 预览装饰器
@Preview
@Component
struct PreviewComponent {
  build() {
    Text('Preview')
  }
}

状态装饰器

typescript
@Component
struct Counter {
  // @State: 组件内部状态
  @State count: number = 0
  
  // @Prop: 父组件传入的属性(单向)
  @Prop title: string
  
  // @Link: 父子组件双向同步
  @Link isVisible: boolean
  
  // @Provide/@Consume: 跨组件层级传递
  @Provide('theme') theme: string = 'light'
  
  build() {
    Column() {
      Text(`${this.title}: ${this.count}`)
      Button('Increment')
        .onClick(() => {
          this.count++
        })
    }
  }
}

监听装饰器

typescript
@Component
struct WatchExample {
  @State count: number = 0
  
  // @Watch: 监听状态变化
  @State @Watch('onCountChange') watchedCount: number = 0
  
  onCountChange() {
    console.log(`Count changed to: ${this.watchedCount}`)
  }
  
  build() {
    Column() {
      Text(`${this.count}`)
      Button('Change')
        .onClick(() => {
          this.watchedCount++
        })
    }
  }
}

声明式 UI

基本结构

typescript
@Entry
@Component
struct BasicUI {
  build() {
    Column() {
      Text('Title')
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
      
      Row() {
        Button('Cancel')
        Button('OK')
      }
      .justifyContent(FlexAlign.SpaceAround)
    }
    .width('100%')
    .height('100%')
    .padding(20)
  }
}

条件渲染

typescript
@Component
struct ConditionalRender {
  @State isLoggedIn: boolean = false
  
  build() {
    Column() {
      if (this.isLoggedIn) {
        Text('Welcome back!')
      } else {
        Text('Please login')
        Button('Login')
      }
    }
  }
}

列表渲染

typescript
@Component
struct ListRender {
  @State items: string[] = ['Item 1', 'Item 2', 'Item 3']
  
  build() {
    Column() {
      // ForEach 循环
      ForEach(this.items, (item: string, index: number) => {
        Text(`${index + 1}. ${item}`)
          .padding(10)
      }, (item: string) => item) // key 生成函数
    }
  }
}

自定义组件

typescript
// 定义组件
@Component
struct UserCard {
  @Prop name: string
  @Prop avatar: string
  @Prop age: number
  
  build() {
    Row() {
      Image(this.avatar)
        .width(50)
        .height(50)
        .borderRadius(25)
      
      Column() {
        Text(this.name)
          .fontSize(18)
          .fontWeight(FontWeight.Bold)
        Text(`${this.age} years old`)
          .fontSize(14)
          .fontColor('#666')
      }
      .alignItems(HorizontalAlign.Start)
      .margin({ left: 10 })
    }
    .padding(15)
  }
}

// 使用组件
@Entry
@Component
struct UserList {
  build() {
    Column() {
      UserCard({
        name: 'Alice',
        avatar: '/path/to/avatar.png',
        age: 25
      })
    }
  }
}

样式设置

基础样式

typescript
Text('Styled Text')
  .width(200)
  .height(50)
  .backgroundColor('#409EFF')
  .fontColor('#FFFFFF')
  .fontSize(18)
  .textAlign(TextAlign.Center)
  .borderRadius(8)
  .padding(10)
  .margin({ top: 20, bottom: 10 })

样式继承

typescript
@Styles function commonButtonStyle() {
  .width(120)
  .height(40)
  .fontSize(16)
  .borderRadius(20)
}

@Component
struct StyledButtons {
  build() {
    Column() {
      Button('Primary')
        .commonButtonStyle()
        .backgroundColor('#409EFF')
      
      Button('Success')
        .commonButtonStyle()
        .backgroundColor('#67C23A')
    }
  }
}

扩展样式

typescript
@Extend(Text) function fancyText(color: string, size: number) {
  .fontColor(color)
  .fontSize(size)
  .fontWeight(FontWeight.Bold)
  .textShadow({ radius: 5, color: '#00000033' })
}

@Component
struct ExtendedText {
  build() {
    Column() {
      Text('Fancy Text')
        .fancyText('#409EFF', 24)
    }
  }
}

事件处理

常用事件

typescript
@Component
struct EventHandling {
  @State message: string = ''
  
  build() {
    Column() {
      // 点击事件
      Button('Click Me')
        .onClick(() => {
          this.message = 'Button clicked!'
        })
      
      // 长按事件
      Text('Long Press')
        .onTouch((event: TouchEvent) => {
          if (event.type === TouchType.Down) {
            console.log('Touch started')
          }
        })
      
      // 输入事件
      TextInput()
        .onChange((value: string) => {
          this.message = value
        })
      
      Text(this.message)
    }
  }
}

手势事件

typescript
@Component
struct GestureExample {
  @State offsetX: number = 0
  @State offsetY: number = 0
  
  build() {
    Column() {
      Text('Drag Me')
        .width(100)
        .height(100)
        .backgroundColor('#409EFF')
        .translate({ x: this.offsetX, y: this.offsetY })
        .gesture(
          PanGesture()
            .onActionUpdate((event: GestureEvent) => {
              this.offsetX = event.offsetX
              this.offsetY = event.offsetY
            })
        )
    }
  }
}

生命周期

typescript
@Entry
@Component
struct LifecycleExample {
  @State count: number = 0
  
  // 组件即将出现
  aboutToAppear() {
    console.log('Component is about to appear')
  }
  
  // 组件即将消失
  aboutToDisappear() {
    console.log('Component is about to disappear')
  }
  
  // 页面显示
  onPageShow() {
    console.log('Page is shown')
  }
  
  // 页面隐藏
  onPageHide() {
    console.log('Page is hidden')
  }
  
  build() {
    Column() {
      Text(`Count: ${this.count}`)
    }
  }
}

最佳实践

1. 状态管理

typescript
// ✅ 推荐:使用 @State 管理组件状态
@State count: number = 0

// ❌ 不推荐:直接修改普通变量
let count = 0

2. 组件拆分

typescript
// ✅ 推荐:拆分成小组件
@Component
struct Header {
  build() { /* ... */ }
}

@Component
struct Content {
  build() { /* ... */ }
}

// ❌ 不推荐:所有代码都在一个组件

3. 性能优化

typescript
// ✅ 推荐:使用 key 优化列表渲染
ForEach(this.items, 
  (item) => { /* ... */ },
  (item) => item.id // 提供唯一 key
)

// ❌ 不推荐:没有 key
ForEach(this.items, (item) => { /* ... */ })

下一步

全栈若城