返回
用“+”号让你的小程序tabBar鹤立鸡群
前端
2023-09-10 12:28:30
在小程序激烈的竞争中,细节往往决定成败。一个设计独特的tabBar,能够让你的小程序脱颖而出,为用户带来更佳的体验。然而,小程序自带的tabBar组件并不支持中间加“+”号这样的设计。
不要担心,通过自定义tabBar组件,我们就能轻松实现这个酷炫的设计。接下来,让我们深入了解如何创建一个带有“+”号的自定义tabBar。
自定义tabBar组件
首先,创建一个名为“CustomTabBar”的新组件。在该组件的WXML文件中,添加以下代码:
<view class="tabbar-container">
<view class="tabbar-item" wx:for="{{tabBarList}}" wx:key="item.path" bindtap="handleTabbar" data-path="{{item.path}}">
<image src="{{item.icon}}" class="tabbar-icon"></image>
<text class="tabbar-text">{{item.text}}</text>
</view>
<view class="tabbar-plus-container" bindtap="handlePlusButton">
<view class="tabbar-plus-icon"></view>
</view>
</view>
CSS样式
接下来,为组件添加CSS样式:
.tabbar-container {
display: flex;
justify-content: space-around;
align-items: center;
width: 100%;
height: 100rpx;
background: #fff;
}
.tabbar-item {
display: flex;
justify-content: center;
align-items: center;
width: 100rpx;
height: 100rpx;
}
.tabbar-icon {
width: 50rpx;
height: 50rpx;
}
.tabbar-text {
font-size: 12px;
color: #999;
}
.tabbar-plus-container {
width: 100rpx;
height: 100rpx;
border-radius: 50%;
background: #f00;
}
.tabbar-plus-icon {
width: 60rpx;
height: 60rpx;
background: #fff;
border-radius: 50%;
}
JavaScript逻辑
最后,添加JavaScript逻辑:
Component({
properties: {
tabBarList: {
type: Array,
value: []
}
},
methods: {
handleTabbar(e) {
// tabBar项点击事件
const path = e.currentTarget.dataset.path;
wx.switchTab({ url: path });
},
handlePlusButton() {
// 加号按钮点击事件
// 自定义事件,具体实现由调用方决定
this.triggerEvent('plusButtonTap');
}
}
});
使用自定义tabBar组件
在需要使用自定义tabBar组件的页面中,添加以下代码:
<custom-tabbar tabBarList="{{tabBarList}}" bind:plusButtonTap="handlePlusButton"></custom-tabbar>
Page({
data: {
tabBarList: [
{
path: '/pages/home/home',
icon: '/images/home.png',
text: '首页'
},
{
path: '/pages/category/category',
icon: '/images/category.png',
text: '分类'
},
{
path: '/pages/plus/plus',
icon: '/images/plus.png',
text: '发现'
},
{
path: '/pages/cart/cart',
icon: '/images/cart.png',
text: '购物车'
},
{
path: '/pages/user/user',
icon: '/images/user.png',
text: '我的'
}
]
},
handlePlusButton() {
// 加号按钮点击事件,具体实现由页面决定
}
});
注意事项
需要判断是否是iPhone X系列的手机,因为iPhone X系列手机的底部安全区域比其他手机更大。可以在组件的JavaScript逻辑中添加以下代码:
const isIphoneX = () => {
const systemInfo = wx.getSystemInfoSync();
return systemInfo.model.search('iPhone X') !== -1 || systemInfo.model.search('iPhone 1') !== -1;
};
在WXML中,添加以下代码:
<view class="tabbar-container" style="{{ isIphoneX() ? 'height: 145rpx;' : 'height: 100rpx;' }}">
这样就能根据手机型号动态调整tabBar的高度,保证在所有手机上都显示正常。