You can customize a tab bar to meet more personalized requirements.
In the tab bar customization mode:
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"
},
{
"pagePath": "page/index2/index"
}
]
}
} 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 custom tab bar code using the custom component, which completely takes over the tab bar rendering. In addition, the getTabBar API is added to obtain the custom tab bar component instance of the current page.
Example:
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 status of the custom tab bar, for example, the selection state and text color.
Page({
onShow() {
if (typeof this.getTabBar === 'function' && this.getTabBar()) {
this.getTabBar().setData({ selected: 1 })
}
}
})