微信小程序自定义tabbar图标切换点击两次才选中解决方法,出现此问题的原因是在切换的页面js没有加入设置状态值getTabBar。
问题:tabbar图标切换 要点击两次才能有选中状态
原因:没有拷贝组件函数
官网中所给出的自定义组件地址:here
在 app.json 中添加:
"tabBar": {
"custom": true,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "组件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
},"usingComponents": {}
然后,在list中至少关联两个页面。在官方示例案例 代码中获取到custom-tab-bar以及对应的image文件,在代码根目录下添加入口文件:
custom-tab-bar/index.js custom-tab-bar/index.json custom-tab-bar/index.wxml custom-tab-bar/index.wxss
然后,简单修改custom-tab-bar/index.js中的list,使得和app.json中定义的一致。然后自己就以为没有了,就会出现标题所示的问题,即:需要点击两次才会切换图标为选中状态。
解决:
需要在每一个关联tabbar的页面的js文件中添加下面的代码:
Component({
pageLifetimes: {
show() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}
}})
其中selected: 0的值需要自己根据顺序指定值。然后,就不会有上述现象了。
当然,此事的页面中默认就是组件,如果需要这种方式使用,需要将每个page页对应的js文件的App删除,然后只保留Component部分,然后如果需要点击函数,就需要采用组件的方式,如:
Component({
pageLifetimes: {
show() {
if (typeof this.getTabBar === 'function' &&
this.getTabBar()) {
this.getTabBar().setData({
selected: 0
})
}
}
},
methods: {
weizu: function(){
console.log(123)
}
}})
在对应的wxml文件中进行事件绑定即可:
<view class="card-range" bindtap="weizu">打卡排行榜</view>
测试发现,其实这种方式不好,存在闪烁现象。
由于之前做过微信小程序的tabbar使用,记得有简单的方式,就考虑将custom-tab-bar文件删除掉,然后将 app.json 中的custom修改下为false:
"tabBar": {
"custom": false,
"color": "#000000",
"selectedColor": "#000000",
"backgroundColor": "#000000",
"list": [{
"pagePath": "page/component/index",
"text": "组件"
}, {
"pagePath": "page/API/index",
"text": "接口"
}]
}
果然可以。就不再考虑使用自定义组件的方式来做tabbar了。


