🌟 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)