1、Tabs的基本使用
@Entry
@Component
struct Index {
private controller: TabsController = new TabsController();
// 声明周期函数
aboutToAppear(){
// 页面加载 1s后 跳转到商城
setTimeout(() => {
this.controller.changeIndex(1)
},1000)
}
build() {
// tabs组件
Column() {
/**
* barPosition: BarPosition.End 设置tabBar的位置
* controller: 控制器
*/
Tabs({ barPosition: BarPosition.End, controller: this.controller }) {
TabContent() {
Text('首页')
}.tabBar('首页')
TabContent() {
Text('商城')
}.tabBar({ icon: $r('app.media.icon') })
TabContent() {
Row({ space: 5 }) {
Text('我的')
Button('去首页').onClick((event: ClickEvent) => {
// 跳转到指定索引TabContent
this.controller.changeIndex(0)
})
}
}.tabBar('我的')
}
// 设置是否排列
// .vertical(true)
}.width('100%')
.padding(20)
}
}
2、自定义Tabs
const tabCustomArr = [
{
id: 1,
name: '首页',
icon: $r('app.media.avatar'),
color: Color.Grey,
activeColor: Color.Orange
},
{
id: 2,
name: '分类',
icon: $r('app.media.icon'),
color: Color.Grey,
activeColor: Color.Green
},
{
id: 3,
name: '商城',
icon: $r('app.media.pig'),
color: Color.Grey,
activeColor: Color.Red
},
{
id: 4,
name: '我的',
icon: $r('app.media.avatar'),
color: Color.Grey,
activeColor: Color.Blue
}
]
@Entry
@Component
struct CustomTabs {
@State currentIndex: number = 0
@Builder tabBuilder(index: number) {
Column() {
Image(tabCustomArr[index].icon).width(30).height(30)
Text(tabCustomArr[index].name)
.fontColor(this.isActive(index) ? tabCustomArr[index].activeColor : tabCustomArr[index].color)
}
}
private isActive(index: number): boolean {
return index === this.currentIndex
}
build() {
Column() {
Tabs({ barPosition: BarPosition.End }) {
TabContent() {
Text('首页')
}.tabBar(this.tabBuilder(0))
TabContent() {
Text('分类')
}.tabBar(this.tabBuilder(1))
TabContent() {
Text('商城')
}.tabBar(this.tabBuilder(2))
TabContent() {
Text('我的')
}.tabBar(this.tabBuilder(3))
}.onChange((index) => {
console.log(index + "")
this.currentIndex = index
})
}.width('100%')
.padding(20)
}
}
标签:index,TabContent,Tabs,Text,HarmonyOS,Color,tabBar,组件,icon
From: https://www.cnblogs.com/ybbit/p/18133495