如何在Taro中使用自定义TabBar

5,410 阅读1分钟

应用场景

tabbar 列表中跳转非tabbar的页面怎么样处理?

代码示例:

//除订单选项,其它全是switchTab
handleTabBar(item) {
  if (item.pagePath.indexOf('order') > -1) {
    Taro.navigateTo({ url: `/${item.pagePath}` });
  } else {
    Taro.switchTab({ url: `/${item.pagePath}` });
  }
}

what?确定在原生 tabbar 行得通?参考以下两篇文章:

自定义 tabBar 微信官方文档

自定义 tabbar 在Taro中的应用

具体步骤

1.src/app.config.js 文件添加 tabBar 项指定 custom 字段

tabBar: {
  custom: true,
  ...
}

2.在 src 下创建 custom-tab-bar 文件夹

//index.config.js
export default {
  component: true
}

//index.jsx
//index.scss

3.通过状态管理管理 tabbar 高亮

componentDidShow(){
  //selected为自定义tabbar list 选中索引
  this.$dispatch({ type: 'tabbar/updateState', payload: { selected: 0 } });
}

优缺点

优点:

1.为tabbar跳转子页面提供解决方案

2.方便自己定义tabbar的样式

缺点:

1.自定义tabbar覆盖页面底部,造成页面部分缺失(可通过样式解决)

2.不能通过原生方法来设置高亮索引(可通过状态管理解决)

//原生操作方法
if (typeof this.getTabBar === 'function' &&
  this.getTabBar()) {
  this.getTabBar().setData({
    selected: 0
  })
}