以下是鴻蒙開發中 所有自定義裝飾器的完整案例解析 和 終極總結指南,涵蓋 16 個核心裝飾器的詳細用法和實戰場景:
一、終極總結表:16大裝飾器全景圖
裝飾器 | 類別 | V1 | V2 | 核心作用 | 典型場景 |
---|---|---|---|---|---|
@Component | 組件定義 | ? | ? | 創建標準組件 | 業務UI組件 |
@ComponentV2 | 組件定義 | ? | ? | 創建可繼承組件 | UI框架基類 |
@State | 狀態管理 | ? | ? | 組件私有狀態 | 計數器、開關狀態 |
@Local | 狀態管理 | ? | ? | V2組件狀態(可繼承) | 可繼承的基類狀態 |
@Prop | 狀態管理 | ? | ? | 父→子單向同步 | 接收父組件數據 |
@Param | 狀態管理 | ? | ? | V2父→子傳參(可繼承) | 可繼承的組件參數 |
@Link | 狀態管理 | ? | ? | 父子雙向綁定 | 表單控件 |
@Provide | 狀態管理 | ? | ? | 跨層級提供數據 | 主題、配置下發 |
@Consume | 狀態管理 | ? | ? | 跨層級消費數據 | 獲取祖先數據 |
@Builder | UI構建 | ? | ? | 定義UI片段 | 復用UI組合 |
@BuilderParam | UI構建 | ? | ? | 聲明動態插槽 | 可配置布局容器 |
@Styles | UI構建 | ? | ? | 復用樣式集 | 統一按鈕/卡片樣式 |
@Extend | UI構建 | ? | ? | 擴展原生組件樣式 | 定制系統組件 |
@Reusable | 性能優化 | ? | ? | V1組件實例復用 | 彈窗/高頻切換組件 |
@ReusableV2 | 性能優化 | ? | ? | V2組件實例復用 | 長列表項 |
@Watch | 輔助 | ? | ? | 監聽狀態變化 | 數據變化回調 |
@Computed | 輔助(V2專屬) | ? | ? | 聲明計算屬性 | 購物車總價 |
二、組件定義裝飾器
1. @Component
(標準組件)
@Component
struct UserCard {
@Prop name: string = "張三"build() {
Column() {
Text(this.name).fontSize(18)
Text("前端開發工程師")
}
}
}
作用:定義可復用的 UI 組件單元
2. @ComponentV2
(實驗性組件)
// @ts-nocheck
@ComponentV2
export struct BaseDialog {
@Local title: string = "系統提示" // V2專屬狀態build() {
Column() {
Text(this.title).fontColor(Color.Red)
this.DialogContent() // 抽象插槽
}
}@BuilderParam DialogContent: () => void = () => Text("默認內容")
}// 繼承基類
@Component
struct ConfirmDialog extends BaseDialog {
@Param message: string // V2專屬傳參@BuilderParam override DialogContent: () => void = () => {
Text(this.message)
Button("確認")
}
}
突破能力:組件繼承、狀態繼承、方法重寫
三、狀態管理裝飾器
3. @State
(組件私有狀態)
@State count: number = 0Button(`點擊 ${this.count}`)
.onClick(() => this.count++) // 觸發UI更新
4. @Local
(V2 組件狀態)
@ComponentV2
struct Counter {
@Local value: number = 0 // 可被子組件繼承build() { ... }
}
5. @Prop
(父→子單向同步)
// 子組件
@Component
struct Child {
@Prop data: string // 接收父組件數據
}// 父組件
Parent() {
Child({ data: parentData }) // 傳遞數據
}
6. @Param
(V2 單向傳參)
@ComponentV2
struct ChildV2 {
@Param message: string // 支持繼承
}
7. @Link
(父子雙向綁定)
// 子組件
@Component
struct Toggle {
@Link isOn: boolean // 雙向綁定
}// 父組件
@State switchState: boolean = false
Toggle({ isOn: $switchState }) // $表示雙向綁定
8. @Provide
/@Consume
(跨層級通信)
// 祖先組件
@Component
struct GrandParent {
@Provide theme: string = "dark"
}// 子孫組件(跳過中間層)
@Component
struct Child {
@Consume theme: string // 直接獲取祖先數據
}
四、UI構建裝飾器
9. @Builder
(UI片段復用)
@Builder function fancyButton(text: string) {
Button(text)
.backgroundColor('#6200EE')
.fontColor(Color.White)
}// 使用
fancyButton("提交")
10. @BuilderParam
(動態插槽)
@Component
struct Card {
@BuilderParam header: () => voidbuild() {
Column() {
this.header() // 動態渲染傳入的UI
}
}
}// 注入內容
Card({ header: () => Text("標題").fontSize(20) })
11. @Styles
(樣式復用)
@Styles function warningStyle() {
.backgroundColor('#FFF8E1')
.borderColor('#FFD740')
}Text("警告信息")
.warningStyle() // 應用樣式集
12. @Extend
(擴展原生樣式)
@Extend(Text) function titleStyle() {
.fontSize(24)
.fontWeight(FontWeight.Bold)
}Text("章節標題")
.titleStyle() // 擴展原生組件
五、緩存復用裝飾器
13. @Reusable
(V1組件緩存)
@Reusable
@Component
struct ExpensiveComponent {
aboutToReuse(params: Object) {
console.log("復用實例", params)
}
}// 使用
ExpensiveComponent().reuseId("comp-1")
14. @ReusableV2
(V2組件緩存)
@ReusableV2
@ComponentV2
struct V2Component {
aboutToReuse() { /* 無參數 */ }
aboutToRecycle() { /* 回收回調 */ }
}// 必須指定reuseId
V2Component().reuse({ reuseId: () => 'v2-comp' })
六、輔助裝飾器
15. @Watch
(狀態監聽)
@State counter: number = 0@Watch('counter')
onCountChange(newValue: number, oldValue: number) {
console.log(`值變化:${oldValue} → ${newValue}`)
}
16. @Computed
(計算屬性-V2專屬)
@ComponentV2
struct Cart {
@State items: Item[] = []@Computed
get totalPrice(): number {
return this.items.reduce((sum, item) => sum + item.price, 0)
}
}
七、三大黃金實踐法則
法則1:裝飾器選型決策樹
graph TD
A[開發組件類型] --> B{是否需繼承?}
B -->|是| C[用@ComponentV2+@Local]
B -->|否| D[用@Component]
D --> E{是否高頻創建?}
E -->|是| F[添加@Reusable]
E -->|否| G[標準實現]
C --> H{是否需緩存?}
H -->|是| I[添加@ReusableV2]
法則2:狀態管理三原則
- 數據流向:
- 單向數據流:
父 → @Prop → 子
- 雙向同步:
父 ? @Link ? 子
- 層級穿透:
- 跨層級:
祖先 @Provide → 子孫 @Consume
- V2優先:
- 繼承場景:
@Local
>@State
,@Param
>@Prop
法則3:性能優化組合拳
場景 | 優化方案 | 效果提升 |
---|---|---|
長列表 | @ReusableV2 + LazyForEach | 滾動幀率提升 300% |
高頻顯示/隱藏 | @Reusable + reuseId | 切換耗時降低 80% |
復雜計算 | @Computed + 緩存策略 | 計算耗時減少 70% |
樣式復用 | @Styles + @Extend | 代碼量減少 60% |
八、避坑指南(血淚經驗)
- TS兼容問題:
// 在V2組件文件頂部添加
// @ts-nocheck
- 裝飾器沖突:
- ? 禁止混用
@State
和@Local
- ? 避免同時使用
@Prop
和@Param
- 緩存陷阱:
// 錯誤!每次創建新ID導致無法復用
.reuse({ reuseId: () => Date.now().toString() })// 正確:相同類型組件使用固定ID
.reuse({ reuseId: () => 'user-card' })
- V2組件限制:
- 不可在
@ComponentV2
中使用@StorageProp
- 禁止跨 V1/V2 組件繼承
九、演進路線圖(2025)
- Q1:
@ComponentV2
結束實驗階段@Computed
支持 V1 組件
- Q2:
- 新增
@Mixin
混入裝飾器 - 推出
@Animate
動畫裝飾器
- Q3:
- 統一 V1/V2 狀態管理模型
- 廢棄
@Local
和@Param
官方資源:
- ArkUI 裝飾器文檔
掌握這些裝飾器組合用法,可大幅提升鴻蒙開發效率和性能表現。建議從 @Component
+ @Prop
+ @Builder
基礎組合起步,逐步探索高級用法。