微信小程序 - 自定義tabBar

微信小程序默認的tabBar只能提供給開發者修改下顏色,然後就沒了。

有的人想要最求個性化的tabBar,比如想要在tab中間加一個巨大的掃碼按鈕,這是很常見的。那麼這時候,自定義tabBar就派上用場了。

做過小程序的應該都知道,定義默認樣式的tabBar可以在app.json 的tabBar 屬性中定義配置tabBar,如下:

{
    ...
    "tabBar": {
    "color": "#666666",
    "selectedColor": "#4d8970",
    "borderStyle": "black",
    "backgroundColor": "#fff",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首頁",
        "iconPath": "images/icon2/home1.png",
        "selectedIconPath": "images/icon2/home2.png"
      },
      {
        "pagePath": "pages/classy/classy",
        "text": "分類",
        "iconPath": "images/icon2/classy1.png",
        "selectedIconPath": "images/icon2/classy2.png"
      }
      {
        "pagePath": "pages/my/my",
        "text": "我的",
        "iconPath": "images/icon2/mine1.png",
        "selectedIconPath": "images/icon2/mine2.png"
      }
    ]
  },
}

一、自定義tabBar實現

1、將tabBar配置爲自定義,custom: true

{
    ...
    "tabBar": {
        "custom": true
    },
}

使用自定義tabBar爲什麼需要添加 custom 屬性並且配置爲true呢,大家可以嘗試在配置了默認tabBar的基礎上添加custom並配置爲true,可以發現,默認的tabBar消失了,儘管你配置的tabBar信息。配置爲true只是爲我們自定義讓出位置。

 

2、編寫自定義tabBar組件

在根目錄添加自定義tabBar文件(名字路徑有嚴格要求)

custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss

用自定義組件的方式編寫即可,該自定義組件完全代替了默認tabBar的渲染。另外,自定義組件新增 getTabBar 接口,可獲取當前頁面下的自定義 tabBar 組件實例。

實際上,即使沒有tabBar,只要我們在app.json中的tabBar屬性中定義爲了tabBar頁就可以通過 wx.switchTab的api進行切換tabBar頁

所以我們可以在自定義tabBar組件中通過wx.switchTab切換頁面即可。

 

可參考官方文檔:傳送門

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章