微信小程序自定义 tabBar 实现方案
为什么需要自定义 tabBar?
原生 tabBar 虽然配置简单,但在实际业务中往往捉襟见肘:不支持中间凸起按钮、图标和文字样式受限、无法动态隐藏或显示,更别提嵌入徽标(Badge)等复杂交互了。
解决方案很明确:使用自定义 tabBar。
本文将带你从零搭建一个支持中间凸起按钮、带动画效果且可扩展的自定义 tabBar 组件。
核心思路
小程序页面是全屏渲染的,我们无法像 H5 那样直接用 fixed 布局覆盖原生 tabBar。正确的做法分三步走:
- 关闭原生 tabBar:在
app.json中移除tabBar配置。 - 手动引入组件:在每个 tab 页面的底部引入自定义 tabBar 组件。
- 模拟切换逻辑:通过
wx.switchTab或wx.navigateTo控制页面跳转。
⚠️ 注意:自定义 tabBar 不是全局组件,必须在每个 tab 页面中单独引入。
第一步:搭建组件结构
先规划好目录,保持整洁:
components/
└── custom-tab-bar/
├── custom-tab-bar.js
├── custom-tab-bar.json
├── custom-tab-bar.wxml
└── custom-tab-bar.wxss
1. 配置组件
在 custom-tab-bar.json 中声明这是一个组件:
{
"component": true,
"usingComponents": {}
}
2. 定义数据与逻辑
JS 文件负责维护 Tab 列表和切换逻辑。这里有个关键点:中间的'发布'按钮通常不是 Tab 页,需要用 navigateTo,而普通 Tab 页用 switchTab。
// components/custom-tab-bar/custom-tab-bar.js
Component({
properties: {
current: {
type: Number,
value:
}
},
: {
: [
{ : , : , : , : },
{ : , : , : , : },
{ : , : , : , : },
{ : , : , : , : },
{ : , : , : , : }
]
},
: {
() {
{ index } = e..;
item = ..[index];
(item.) {
wx.({ : });
;
}
wx.({ : item. });
.(, { index });
}
}
});

