目錄
一、基礎語法
二、聲明式 UI 開發
基本組件結構
三、狀態管理
四、生命周期鉤子
五、組件化開發
1. 創建自定義組件
2. 組件嵌套
六、事件處理
七、布局系統
八、樣式設置
九、條件渲染與列表渲染
十、異步操作
十一、路由導航
開發建議
一、基礎語法
ArkTS 是 TypeScript 的超集,所以支持所有 TypeScript 的特性,包括:
-
類型注解
let name: string = "張三"; let age: number = 25; let isStudent: boolean = true;
-
接口
interface Student {id: number;name: string;score?: number; // 可選屬性 }
-
類
class Animal {constructor(public name: string) {}move(distance: number = 0) {console.log(`${this.name} moved ${distance}m.`);} }
-
函數
function greet(name: string): string {return `Hello, ${name}!`; }
二、聲明式 UI 開發
ArkTS 采用聲明式語法構建 UI,類似于 React 和 Vue 的 JSX。
基本組件結構
@Entry // 應用入口組件
@Component // 聲明為自定義組件
struct MyComponent {@State count: number = 0; // 響應式狀態build() { // 構建UI的方法Column() { // 垂直布局容器Text(`Count: ${this.count}`).fontSize(30)Button('Increment').onClick(() => {this.count++; // 狀態變化會自動更新UI})}.width('100%').height('100%')}
}
三、狀態管理
ArkTS 提供多種狀態管理方式:
-
@State - 組件內部狀態
@State private isActive: boolean = false;
-
@Link - 父子組件雙向綁定
// 父組件 @State parentValue: string = "初始值";// 子組件 @Link childValue: string;
-
@Provide/@Consume - 跨組件狀態共享
// 提供者 @Provide theme: string = "dark";// 消費者 @Consume theme: string;
四、生命周期鉤子
ArkTS 組件生命周期:
@Component
struct LifecycleDemo {aboutToAppear() { // 組件即將顯示console.log('組件即將掛載');}aboutToDisappear() { // 組件即將銷毀console.log('組件即將卸載');}onPageShow() { // 頁面顯示console.log('頁面顯示');}onPageHide() { // 頁面隱藏console.log('頁面隱藏');}
}
五、組件化開發
1. 創建自定義組件
@Component
struct CustomButton {@Prop label: string = "按鈕";@State isPressed: boolean = false;build() {Button(this.label).stateEffect(this.isPressed).onClick(() => {this.isPressed = !this.isPressed;})}
}
2. 組件嵌套
@Component
struct Card {@Prop header: string;@Prop content: string;build() {Column() {Text(this.header).fontSize(20)Divider()Text(this.content)}.borderRadius(10).padding(15)}
}
六、事件處理
ArkTS 支持多種事件類型:
Button('交互按鈕').onClick(() => {}) // 點擊.onLongPress(() => {}) // 長按.onTouch(() => {}) // 觸摸TextInput().onChange((value: string) => {}) // 輸入變化Swiper().onChange((index: number) => {}) // 滑動變化
七、布局系統
ArkTS 提供豐富的布局容器:
-
Flex 布局
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.SpaceBetween }) {Text('Item1')Text('Item2') }
-
Grid 布局
Grid() {ForEach([1,2,3,4], (item) => {Text(`Item${item}`)}) } .columnsTemplate("1fr 1fr")
-
Stack 布局
Stack() {Image('background.jpg')Text('水印') }
八、樣式設置
ArkTS 提供鏈式調用的樣式API:
Text('樣式示例').fontSize(16).fontColor(Color.White).backgroundColor('#007DFF').borderRadius(8).padding(10).margin({ top: 5, bottom: 5 }).width('90%').height(40)
九、條件渲染與列表渲染
-
條件渲染
@State showDetails: boolean = false;build() {Column() {if (this.showDetails) {Text('詳細信息')}} }
-
列表渲染
@State items: string[] = ['Apple', 'Banana', 'Orange'];List() {ForEach(this.items, (item, index) => {ListItem() {Text(item)}}) }
十、異步操作
ArkTS 支持現代異步編程方式:
async fetchData() {try {const response = await fetch('https://api.example.com/data');const data = await response.json();this.dataList = data;} catch (error) {console.error('請求失敗:', error);}
}
十一、路由導航
ArkTS 提供完整的路由系統:
// 導航到新頁面
router.pushUrl({url: 'pages/Detail',params: { id: 123 }
});// 接收參數
aboutToAppear() {const params = router.getParams();this.id = params['id'];
}// 路由返回
router.back();
開發建議
- 使用 DevEco Studio 進行開發
- 參考官方文檔: HarmonyOS開發者官網
- 從簡單示例開始,逐步構建復雜應用
- 合理使用狀態管理,避免過度嵌套
- 注意性能優化,特別是列表渲染場景