由于业务需求,产品需要自定义tabbar,一直用taro-rn mobx模式编写代码,用起来还行,但是编译速度极慢,主包无论怎么分包都还是快2M,导致dev模式下根本没办法预览,坑已经掉进去了,无法弃·····
tabbar自定义。
网上找了很多方法,发现
componentDidShow(){
if(typeof this.$scope.getTabBar==='function'&&this.$scope.getTabBar()){
this.$scope.getTabBar().$component.setState({selected:0})
}
}
taro 3.0.14 没有$scope 也没有getTabBar方法.....坑!
最后在getCurrentPage 方法返回中找到了getTabBar , 但是无论怎么setData都无效
const page = getCurrentPages()[0]
if (typeof page.getTabBar === 'function' && page.getTabBar()) {
console.log(page.getTabBar())
page.getTabBar().setData({
selected: 1
})
}
无奈,最后分析其原理,上面这串代码在做什么? 其实是拿到了tabbar实例,修改其index,
那如果我能用store内的属性注入来修改index是不是一样的效果?
do it!
给tabbar文件绑定一个store。
store.js
import { observable, action } from "mobx";
class TabbarStore {
//从后台获取来的数据拆分成两个数组,用于页面的左分类和右列表
@observable.ref index = 0
@action.bound
setIndex = (index) => {
this.index = index
}
}
export default new TabbarStore();
然后tabbar文件
import Taro, { getCurrentInstance } from '@tarojs/taro'
import React, { Component } from 'react'
import { View, CoverView, CoverImage, Text, Radio } from '@tarojs/components'
import { observer, inject } from 'mobx-react'
import { AtTabs, AtTabsPane, AtCurtain } from 'taro-ui'
import './index.scss'
@inject('store')
@observer
class YCTabbar extends Component {
constructor(props) {
super(props)
this.state = {
selected: 0,
color: 'rgba(68, 68, 68, 1)',
selectedColor: 'rgba(68, 68, 68, 1)',
list: [
{
pagePath: 'pages/componentsHome/index',
text: '首页',
iconPath: '../assets/tab_home.png',
selectedIconPath: '../assets/tab_home_selected.png'
},
{
pagePath: 'pages/my/index',
text: '我的',
iconPath: '../assets/tab_cate.png',
selectedIconPath: '../assets/tab_cate_selected.png'
}
]
}
}
handleTab(path){
console.log(path)
Taro.switchTab({
url:'../../' + path
})
}
render() {
const { list, selected,selectedColor,color } = this.state
const { store : { tabbarStore : {index}}} = this.props
console.log('当前index',index)
return (
{
list && list.map((item,index1) => (
))
}
)
}
}
export default YCTabbar
之后在页面内的componentDidShow 中去修改index即可
componentDidShow() {
const page = getCurrentPages()[0]
console.log('gettabbar ',page)
const {store : {tabbarStore : { setIndex }}} = this.props
setIndex(0)
}
再说一次,taro is shit ,fuck you taro!