You can customize a tab bar to meet more personalized requirements.
In the tab bar customization mode:
You need to provide a custom component to render the tab bar and implement its interactions.
After tab bar customization is enabled, APIs has.hideTabBar and has.showTabBar remain available, while other APIs such as has.setTabBarBadge become invalid.
Each page has a distinct instance of the custom tab bar component. You can call the getTabBar API to obtain the custom tab bar component instance of the current page.
Configure relevant information.
Add the custom field to the existing tab bar configurations in the app.json file.
Code snippet in the app.json file:
{
"pages": [
"page/index1/index",
"page/index2/index"
],
"tabBar": {
"custom": true,
"list": [
{
"pagePath": "page/index1/index",
"text": "custom_tab1"
},
{
"pagePath": "page/index2/index",
"text": "custom_tab2"
}
]
}
} Place the tab bar entry file in the code root directory, and name the custom tab bar folder custom-tab-bar.
Directory structure example:
├── custom-tab-bar │ ├── index.css │ ├── index.hxml │ ├── index.js │ └── index.json ├── components │ └── ... ├── pages │ └── ... ├── app.css ├── app.js ├── app.json ├── ascf.config.json └── ...
Write the code for your custom tab bar. Use a custom component to implement the custom tab bar, and this component takes full control of its rendering. In addition, the getTabBar API is added to obtain the custom tab bar component instance of the current page.
Examples:
custom-tab-bar/index.hxml:
<view class="tab-bar">
<view
has:for="{{list}}"
has:key="index"
class="tab-item {{selected === index ? 'selected-tab' : ''}}"
bindtap="switchTab"
data-path="{{item.pagePath}}">
<view>{{ item.text }}</view>
</view>
</view> custom-tab-bar/index.js:
Component({
data: {
selected: 0, // Selected index
list: [
{
"pagePath": '/page/index1/index',
"text": 'custom_tab1'
},
{
"pagePath": '/page/index2/index',
"text": 'custom_tab2'
}
]
},
methods: {
switchTab(e) {
const path = e.currentTarget.dataset.path;
has.switchTab({
url: path
});
}
}
}); custom-tab-bar/index.css:
.tab-bar {
position: fixed;
bottom: 0;
width: 100%;
height: 150rpx;
display: flex;
background: #FFFFFF;
box-shadow: 0 -2rpx 6rpx rgba(0, 0, 0, 0.06);
}
.tab-item {
flex: 1;
text-align: center;
padding: 10rpx 0;
}
.selected-tab {
color: #FF4500;
} pages/index2/index.js:
During page switching, you need to manually update the state of the custom tab bar, for example, its selected state and text color.
Page({
onShow() {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({ selected: 1 });
}
}
});