通过页签进行内容视图切换的容器组件,每个页签对应一个内容视图。包含子组件TabContent
Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: TabsController})
参数
- barPosition 设置Tabs的页签位置
- BarPosition枚举
- Start vertical为true,容器左侧;为false,容器顶部
- End vertical为true,容器右侧;为false,容器底部
- BarPosition枚举
- index 当前页签索引
- controller Tabs控制器
Tabs属性
- vertical 设置页签排列方向 true/false
- scrollable 设置是否滑动切换 true/false
-
- barMode
- BarMode枚举
- Scrollable 滚动
- Fixed 固定
- BarMode枚举
- barMode
- animationDuration 设置动画时长 ms
- animationMode 点击TabBar页签时切换TabContent的动画形式
- divider TabBar和TabContent的分割线样式
- barBackgroundColor 设置TabBar的背景颜色
- tabBar 设置导航栏内容
- string 设置导航栏文字
- Builder 设置组件Builder组件
Tabs事件
-
onChange(event: (index: number) => void) 监听点击元素,index是点击元素索引
-
onTabBarClick(event: (index: number) => void) 监听切换元素,index是切换元素索引
constructor
let controller: TabsController = new TabsController()
- changeIndex(value: number)
控制Tabs切换到指定页签
Tabs页签的使用
- 方式一
Tabs(){
TabConent(){
xxx
}.tabBar('首页')
TabConent(){
xxx
}.tabBar('我的')
}
- 方式二
Tabs(){
ForEach(this.list,(item:TabItem,index:number)=>{
TabContent(){
xxx
}
}).tabBar(this.TabItemBuilder(item, index))
}
@Builder
TabItemBuilder(item: TabItem, index: number) {
Column() {
Image(this.activeIndex === index ? item.active : item.normal)
.width(24)
.aspectRatio(1)
Text(item.text)
.fontColor($r('app.color.black'))
.fontSize(12)
}
.justifyContent(FlexAlign.SpaceEvenly)
.height(50)
}
Tabs使用的注意点
- 在布局页面的页面中,部分手机会有底部条块,我们进行底部导航区规避
- 在
windowStage.loadContent的回调函数中,获取底部导航区的避让像素px,将px转换为vp存储到AppStorage中进行存储
const bottom = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR)
.bottomRect
AppStorage.setOrCreate<number>('safeBottom', px2vp(bottom.height))
- 获取AppStorage的安全距离,给Tabs设置
padding-bottom
@StorageProp('safeBottom') safeBottom: number = 0
Tabs(){
xxx
}
.padding({ bottom: this.safeBottom })
- 因为Tabs是一次性加载所有的TabContent组件,会导致TabContent加载过就不会再加载,我们可以通过条件渲染进行改进,保证TabContent可以多次调用
Tabs(){
ForEach(this.list,(item:TabItem,index:number)=>{
TabContent(){
if(index===0){
homeView()
}else if(index===1){
myView()
}
}
}).tabBar(this.TabItemBuilder(item, index))
}