HarmonyOS NEXT應用開發之Tab元件實現增刪Tab標籤

生活就是这么怪發表於2024-04-18

介紹

本示例介紹使用了Tab元件實現自定義增刪Tab頁籤的功能。該場景多用於瀏覽器等場景。

效果圖預覽

使用說明

  1. 點選新增按鈕,新增Tab頁面。
  2. 點選刪除按鈕,刪除Tab頁面。

實現思路

  1. 設定Tab元件的barHeight為0,隱藏元件自帶的TabBar。
Tabs() {
  ...
}
.barHeight(0) // 隱藏tab元件自帶的tabbar
  1. 使用@Link修飾符,將自定義TabBar元件和Tab元件透過focusIndex和tabArray進行雙向繫結。
//TabSheetComponent.ets
@Component
struct TabSheetComponent {
  @Link tabArray: Array<number>
  @Link focusIndex: number

  build() {
    ...
  }
}
    
//HandleTabs.ets
@Component
struct HandleTabs {
  @State tabArray: Array<number> = [0]; // 控制頁籤渲染的陣列
  @State focusIndex: number = 0; // Tabs元件當前顯示的頁簽下標

  build() {
    ...

    TabSheetComponent({ tabArray: $tabArray, focusIndex: $focusIndex })
    Tabs({ index: this.focusIndex }) {
      ForEach(this.tabArray,()=>{
        ...
      })
    }

    ...
  }
}
  1. 在自定義TabBar中修改focusIndex和tabArray的值時,Tab元件根據資料變化進行對應UI變更
//TabSheetComponent.ets
Image('add') // 新增頁籤
  .onClick(() => {
    this.tabArray.push(item)
  })

...

Image('close') // 關閉指定索引頁籤
  .onClick(() => {
    this.tabArray.splice(index, 1)
  })

...

this.focusIndex = index; // 跳轉到指定索引值

高效能知識點

本示例使用了ForEach進行資料懶載入,ForEach第三個入參keyGenerator唯一時,動態修改ForEach時,可降低渲染開銷。

工程結構&模組型別

handletabs                                      // har包
|---model
|   |---constantsData.ets                       // 定義常量資料
|---pages                        
|   |---HandleTabs.ets                          // 增刪tab頁籤功能實現頁面
|   |---MenuBar.ets                             // 工具欄
|   |---TabSheetComponent.ets                   // 自定義TabBar元件

模組依賴

當前場景依賴common模組的FunctionDescription元件,主要用於功能場景文字介紹。詳細可參考FunctionDescription檔案。

參考資料

ForEach使用說明

Tabs元件使用說明

相關文章