鴻蒙開發筆記-3-自定義組件基礎

一、組件架構設計原理

1.1 組件化核心機制

HarmonyOS自定義組件基于ArkUI框架構建,采用聲明式UI編程模型,通過@Component裝飾器實現組件封裝。其核心特性包括:

  • 原子化設計:每個組件獨立管理狀態與樣式
  • 響應式更新:通過@State/@Prop等裝飾器實現數據驅動UI
  • 跨設備適配:支持一次開發多端部署的彈性布局

1.2 組件生命周期全解析

頁面級生命周期(@Entry組件):

@Component
struct PageComponent {
  onPageShow() { /* 頁面顯示時觸發 */ }
  onPageHide() { /* 頁面隱藏時觸發 */ }
  onBackPress() { /* 物理返回鍵處理 */ }
}

組件級生命周期:

@Component
struct MyComponent {
  aboutToAppear() { /* 組件實例化后執行 */ }
  onDidBuild() { /* UI構建完成后觸發 */ }
  aboutToDisappear() { /* 組件銷毀前執行 */ }
}

生命周期管理最佳實踐:

  • 避免在aboutToDisappear中修改狀態變量
  • 使用onDidBuild進行埋點數據上報
  • 頁面切換時凍結非活躍組件

二、組件通信模式進階

2.1 數據傳遞模式對比

方式 數據流向 適用場景 性能影響
@Prop 父→子單向 簡單參數傳遞
@Link 雙向綁定 表單控件交互
@Provide/@Consume 跨層級傳遞 主題切換/全局配置
EventEmitter 子→父事件 復雜交互場景

2.2 動態參數處理

使用@Builder構建可復用UI片段:

@Builder
function DynamicHeader(title: string) {
  Row() {
    Text(title).fontSize(18)
    Image($r('app.media.icon'))
  }
}

@Component
struct ProfilePage {
  build() {
    Column() {
      DynamicHeader("用戶資料")
    }
  }
}

三、高級布局與交互實現

3.1 自定義布局引擎

重寫布局方法實現瀑布流效果:

@Component
struct WaterfallLayout {
  onMeasureSize() {
    // 計算子組件尺寸
    children.forEach(child => {
      child.measure({ width: 100, height: 150 })
    })
  }

  onPlaceChildren() {
    // 動態排列子組件位置
    let x = 0, y = 0
    children.forEach((child, index) => {
      child.place({ x, y })
      y += (index % 2 === 0) ? 160 : 120
    })
  }
}

3.2 復雜交互組件開發

實現可拖拽排序列表:

@Component
struct DraggableList {
  @State items: string[] = ['Item1', 'Item2', 'Item3']
  
  build() {
    List() {
      ForEach(this.items, (item, index) => {
        ListItem() {
          Text(item)
            .gesture(
              PanGesture()
                .onActionUpdate((event) => {
                  // 處理拖拽邏輯
                })
            )
        }
      })
    }
  }
}

四、性能優化體系

4.1 渲染優化策略

  • 節點精簡:使用@Reusable實現組件復用
  • 懶加載:LazyForEach處理長列表
  • 狀態凍結:freezeWhenInactive控制非活躍組件

4.2 內存管理技巧

優化手段 實現方式 適用場景
對象池技術 復用組件實例 高頻創建/銷毀場景
圖片壓縮 使用WebP格式+分辨率適配 圖片密集型應用
大數據分頁 分頁加載+滾動緩存 列表展示場景

五、企業級開發實踐

5.1 導航欄組件封裝

實現多形態導航欄:

@Component
struct CustomNavBar {
  @Prop title: string
  @Prop showBack: boolean = true
  
  build() {
    Row() {
      if (this.showBack) {
        Image($r('app.media.back'))
          .onClick(() => zrouter.pop())
      }
      Text(this.title).flexGrow(1)
    }
    .padding(10)
    .backgroundColor(Color.White)
  }
}

5.2 日歷組件開發

集成日程管理功能:

@Component
struct Calendar {
  @State selectedDate: Date = new Date()
  @Prop events: EventData[]
  
  build() {
    Grid() {
      ForEach(this.generateDays(), (day) => {
        GridItem() {
          Text(day.date)
            .backgroundColor(this.getDayColor(day))
            .onClick(() => this.selectDate(day))
        }
      })
    }
  }
  
  private getDayColor(day: DayInfo): Color {
    return this.events.some(e => e.date === day.date) ? Color.Red : Color.White
  }
}

我是今陽,如果想要進階和了解更多的干貨,歡迎關注wxgzh“今陽說” 接收我的最新文章

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容