๐ ArkTS Demystified: Build Modern UI with HarmonyOS Declarative Syntax
ArkTS is the beating heart of HarmonyOS 5.0+. It's concise, reactive, and tailor-made for multi-device development. Letโs build a modern UI and understand how it works.
๐ What is ArkTS?
ArkTS is a TypeScript-inspired declarative UI language in HarmonyOS. Think of it as the best of SwiftUI + React Native โ but for distributed apps.
๐ฏ Our Goal
Weโll build a reusable Counter
component with:
- State management
- Event handling
- Component composition
๐งฑ Step 1: Create a Counter Component
File: entry/src/main/ets/components/Counter.ets
@Component
export struct Counter {
@State count: number = 0;
build() {
Column() {
Text(`Count: ${this.count}`)
.fontSize(24)
.margin(12)
Row() {
Button('-')
.onClick(() => this.count--)
.margin(8)
Button('+')
.onClick(() => this.count++)
.margin(8)
}
}
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
.width('100%')
.height('100%')
}
}
๐ ๏ธ Step 2: Use the Counter in Index Page
File: pages/Index.ets
import { Counter } from '../components/Counter';
@Component
struct IndexPage {
build() {
Column() {
Text('Welcome to ArkTS Counter')
.fontSize(28)
.fontWeight(FontWeight.Bold)
.margin(16)
Counter()
}
.width('100%')
.height('100%')
}
}
๐ฎ Run Result
- Shows title + counter value
- Click
+
/-
to increment/decrement - Full reactive re-rendering on state update
๐ผ๏ธ UI Preview:
[ Welcome to ArkTS Counter ]
[ Count: 0 ]
[ [-] [+] ]
โ ๏ธ Easy Mistakes to Avoid
Mistake | Cause | Fix |
---|---|---|
count doesn't update UI |
Forgot @State
|
Add @State before the variable |
Buttons unresponsive | Wrong method syntax | Use arrow functions: () => this.count++
|
Error: โCounter not foundโ | Wrong path or forgot export
|
Ensure export is used + import path correct |
Layout not centered | No .alignItems() or .justifyContent()
|
Add them to the layout container |
๐ Summary
You now know how to:
- Define reusable UI components
- Use ArkTS stateful logic
- Build layouts using
Column
,Row
,Text
, andButton
๐ฎ Coming Next...
In the next post, weโll explore distributed app development with HarmonyOS โ build once, run on multiple devices!
๐ Subscribe for more hands-on HarmonyOS guides. Letโs master ArkTS together.
Top comments (0)