小程序自定义tabbar
1. 配置信息
在 app.json 中的 tabBar 项指定 custom 字段,同时其余 tabBar 相关配置也补充完整。可以去掉list不影响,但是tabBar这个配置一定要保留,即便里面是空,也要保留,不然自定义的tabbar不会出现在页面中。
"tabBar": {
"custom": true,
"color": "#a9b7b7",
"selectedColor": "#11cd6e",
"borderStyle": "black" ,
"list": [{
"selectedIconPath": "images/tabs/home-active.png",
"iconPath": "images/tabs/home.png",
"pagePath": "pages/index/index",
"text": "首页"
}, {
"selectedIconPath": "images/tabs/message-active.png",
"iconPath": "images/tabs/message.png",
"pagePath": "pages/message/message",
"text": "消息页"
},{
"selectedIconPath": "images/tabs/contact-active.png",
"iconPath": "images/tabs/contact.png",
"pagePath": "pages/concact/concact",
"text": "联系页"
}
]
},
2. 添加 tabBar 代码文件
1) 从官网下载案例,如下:
2) 下载后的代码如下
3) 接着把custom-tab-bar整个文件拷贝到你的项目下:
4) 修改custom-tab-bar/index.js的文件
data: {
selected: 0,
color: "#7A7E83",
selectedColor: "#3cc51f",
list: [{
pagePath: "/pages/index/index",
selectedIconPath: "/images/tabs/home-active.png",
iconPath: "/images/tabs/home.png",
text: "首页"
}, {
pagePath: "/pages/message/message",
selectedIconPath: "/images/tabs/message-active.png",
iconPath: "/images/tabs/message.png",
text: "消息"
}
, {
pagePath: "/pages/concact/concact",
selectedIconPath: "/images/tabs/contact-active.png",
iconPath: "/images/tabs/contact.png",
text: "联系"
}
]
}
到此运行代码之后会发现:tabbar图标切换 要点击两次才能有选中状态
原因:切换每个页面的selected未修改,可继续借鉴custom-tab-bar案例,案例里面的两个页面还有这段代码:
Component({
pageLifetimes: {
show() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 1
})
}
}
}
})
所以解决方法,在我们的页面里面也添加show方法改变selected
onShow: function () {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({
selected: 2
})
}
}
最终切换效果正常: