taro底部导航,Tabbar
没有特别的幸运,那么就特别的努力!!!
配置信息
官方给出:
在 app.config 中按正常填写 tabBar 项的相关配置(为了向下兼容),并把 tabBar 项的 custom 字段设置为 true。但我试过 custom设置为 false 才生效
1.app.config.js 文件配置
// app.config.js
export default defineAppConfig({pages: ["pages/index/index", "pages/complaint/index", "pages/mine/index"],window: {backgroundTextStyle: "light",navigationBarBackgroundColor: "#fff",navigationBarTitleText: "WeChat",navigationBarTextStyle: "black",},tabBar: {custom: false,color: "#000000",selectedColor: "#DC143C",backgroundColor: "#ffffff",list: [{pagePath: "pages/index/index",selectedIconPath: "images/tabbar_home_on.png",iconPath: "images/tabbar_home.png",text: "首页",},{pagePath: "pages/mine/index",selectedIconPath: "images/tabbar_my_on.png",iconPath: "images/tabbar_my.png",text: "个人中心",},],},
});
2.添加 custom-tab-bar
在 src 目录下添加 custom-tab-bar 目录,在里面书写组件,支持 React、Vue 和原生写法。
├── config
├── src
| └── custom-tab-bar
| ├── index.config.ts
| └── index.tsx
└── package.json
// src/custom-tab-bar/index.tsx
import { Component } from 'react'
import Taro from '@tarojs/taro'
import { CoverView, CoverImage } from '@tarojs/components'import './index.scss'export default class Index extends Component {state = {selected: 0,color: '#000000',selectedColor: '#DC143C',list: [{pagePath: '/pages/index/index',selectedIconPath: '../images/tabbar_home_on.png',iconPath: '../images/tabbar_home.png',text: '首页'},{pagePath: '/pages/mine/index',selectedIconPath: '../images/tabbar_my_on.png',iconPath: '../images/tabbar_my.png',text: '个人中心'}]}switchTab(index, url) {this.setSelected(index)Taro.switchTab({ url })}setSelected (idx: number) {this.setState({selected: idx})}render() {const { list, selected, color, selectedColor } = this.statereturn (<CoverView className='tab-bar'><CoverView className='tab-bar-border'></CoverView>{list.map((item, index) => {return (<CoverView key={index} className='tab-bar-item' onClick={this.switchTab.bind(this, index, item.pagePath)}><CoverImage src={selected === index ? item.selectedIconPath : item.iconPath} /><CoverView style={{ color: selected === index ? selectedColor : color }}>{item.text}</CoverView></CoverView>)})}</CoverView>)}
}
3.底部组件都需要引入
// src/page/mine/index.tsx
import { View, Text } from '@tarojs/components'
import Taro,{ useLoad } from '@tarojs/taro'
import './index.scss'import type CustomTabBar from '../../custom-tab-bar'export default function Mine () {const pageCtx = Taro.getCurrentInstance().pageuseLoad(() => {const tabbar = Taro.getTabBar<CustomTabBar>(pageCtx)tabbar?.setSelected(1)})return (<View className='mine'><Text>mine-1</Text></View>)
}
希望能帮助到大家,同时祝愿大家在开发旅途中愉快!!!
拿着 不谢 请叫我“锤” !!!