import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
export default class CustomTabBar extends Taro.Component {
constructor(props) {
super(props)
this.state = {
current: 0, // 当前激活的tab索引
}
}
// 根据页面路由切换Tab
switchTab(path) {
const { tabs } = this.props
const current = tabs.findIndex(item => item.pagePath === path)
this.setState({ current })
}
// 根据点击切换Tab
handleTabClick(index, pagePath) {
const { current } = this.state
if (index !== current) {
this.setState({ current: index })
Taro.navigateTo({ url: pagePath })
}
}
render() {
const { current } = this.state
const { tabs } = this.props
return (
<View>
{tabs.map((item, index) => (
<View
key={item.pagePath}
className={`tab-item ${current === index ? 'active' : ''}`}
onClick={this.handleTabClick.bind(this, index, item.pagePath)}
>
{item.text}
</View>
))}
</View>
)
}
}
这段代码示例展示了如何在Taro小程序中创建一个自定义的底部Tab栏,并处理Tab的点击切换逻辑,避免卡顿和闪烁问题。通过合理使用setState
和navigateTo
,确保了在用户点击Tab时不会出现页面的卡顿或闪烁。