自定義 tabBar
基礎(chǔ)庫 2.5.0 開始支持,低版本需做兼容處理。
自定義 tabBar 可以讓開發(fā)者更加靈活地設(shè)置 tabBar 樣式,以滿足更多個(gè)性化的場(chǎng)景。
在自定義 tabBar 模式下
- 為了保證低版本兼容以及區(qū)分哪些頁面是 tab 頁,tabBar 的相關(guān)配置項(xiàng)需完整聲明,但這些字段不會(huì)作用于自定義 tabBar 的渲染。
- 此時(shí)需要開發(fā)者提供一個(gè)自定義組件來渲染 tabBar,所有 tabBar 的樣式都由該自定義組件渲染。推薦用 fixed 在底部的 cover-view + cover-image 組件渲染樣式,以保證 tabBar 層級(jí)相對(duì)較高。
- 與 tabBar 樣式相關(guān)的接口,如 wx.setTabBarItem 等將失效。
- 每個(gè) tab 頁下的自定義 tabBar 組件實(shí)例是不同的,可通過自定義組件下的
getTabBar
接口,獲取當(dāng)前頁面的自定義 tabBar 組件實(shí)例。
注意:如需實(shí)現(xiàn) tab 選中態(tài),要在當(dāng)前頁面下,通過 getTabBar 接口獲取組件實(shí)例,并調(diào)用 setData 更新選中態(tài)??蓞⒖嫉撞康拇a示例。
使用流程
1. 配置信息
- 在
app.json
中的tabBar
項(xiàng)指定custom
字段,同時(shí)其余tabBar
相關(guān)配置也補(bǔ)充完整。 - 所有 tab 頁的 json 里需聲明
usingComponents
項(xiàng),也可以在app.json
全局開啟。
示例:
{
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "組件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
},
"usingComponents": {}
}
2. 添加 tabBar 代碼文件
在代碼根目錄下添加入口文件:
custom-tab-bar/index.js
custom-tab-bar/index.json
custom-tab-bar/index.wxml
custom-tab-bar/index.wxss
3. 編寫 tabBar 代碼
用自定義組件的方式編寫即可,該自定義組件完全接管 tabBar 的渲染。另外,自定義組件新增 getTabBar
接口,可獲取當(dāng)前頁面下的自定義 tabBar 組件實(shí)例。
示例代碼
skyline 模式
使用 skyline 渲染模式的時(shí)候,需要進(jìn)行如下適配:
1. tabBar 組件樣式兼容
- tabBar 根組件需要添加
pointer-events: auto
- tabBar 根組件定位需為
position: absolute
<view class="tab-bar">
<!-- tabbar item-->
</view>
.tab-bar {
pointer-events: auto;
position: absolute;
}
2. getTabBar 回調(diào)函數(shù)
skyline 模式下,頁面/組件上的 getTabBar
接口為異步回調(diào)的方式獲取 tabBar 實(shí)例
Page({
getInstance() {
if (typeof this.getTabBar === 'function' ) {
this.getTabBar((tabBar) => {
tabBar.setData({
selected: 0
})
})
}
}
})