为什么要放弃原生 tabBar
原生 tabBar 虽然简单易用,但在样式定制上捉襟见肘:不支持中间凸起按钮,图标和文字样式难以高度自定义,也无法动态隐藏或嵌入业务徽标。这时候,自定义 tabBar 就成了必选项。本文将带你从零实现一个支持中间凸起按钮、带动画且可扩展的自定义 tabBar,并封装为通用组件。
核心思路
小程序页面是全屏渲染的,我们无法像 H5 那样直接用 fixed 布局覆盖原生 tabBar。正确的做法是关闭原生 tabBar 配置,在每个页面底部手动引入自定义 tabBar 组件,并通过 wx.switchTab 或 wx.navigateTo 模拟 tab 切换。需要注意的是,自定义 tabBar 并非全局组件,需在每个 tab 页面中手动引入。
搭建自定义组件
先确定目录结构,创建一个名为 custom-tab-bar 的组件文件夹。
// components/custom-tab-bar/custom-tab-bar.js
Component({
properties: {
current: { type: Number, value: 0 }
},
data: {
tabs: [
{ pagePath: "/pages/home/index", text: "首页", icon: "home", selectedIcon: "home-fill" },
{ pagePath: "/pages/category/index", text: "分类", icon: "category", selectedIcon: "category-fill" },
{ pagePath: "/pages/publish/index", text: "", icon: "add", isCenter: true },
{ pagePath: "/pages/cart/index", text: "购物车", icon: "cart", selectedIcon: },
{ : , : , : , : }
]
},
: {
() {
{ index } = e..;
item = ..[index];
(item.) {
wx.({ : });
;
}
wx.({ : item. });
.(, { index });
}
}
});

