Tabs 与 TabBar 基础
Tabs 组件由 TabBar(页签导航栏)和 TabContent(对应内容区)两部分组成。TabBar 作为导航入口,其布局模式直接影响页面美观与操作流畅度。
核心属性:barMode
- 作用:定义
TabBar的布局规则,控制页签宽度分配与滚动能力 - 类型:
BarMode枚举,包含两种核心模式BarMode.Fixed:固定均分模式(默认值)BarMode.Scrollable:可滚动模式
- 配置位置:
Tabs组件的链式调用属性
两种布局模式
1. BarMode.Fixed(固定均分模式)
核心特性
- 宽度均分:所有
TabBar页签自动平均分配TabBar总宽度,每个页签宽度完全一致 - 不可滚动:
TabBar区域固定,无法横向滑动,页签数量超出屏幕宽度时会被挤压截断 - 布局稳定:页签位置固定,适合数量少、内容固定的导航场景
适用场景
- 应用底部导航栏(通常 3-5 个固定页签,如首页、分类、我的)
- 页签数量固定且较少(≤5 个),无需动态扩展的场景
- 要求导航栏布局稳定、无滚动行为的界面
代码配置
Tabs(){
// TabContent 定义...
}.barMode(BarMode.Fixed) // 配置固定均分模式
2. BarMode.Scrollable(可滚动模式)
核心特性
- 自适应宽度:每个
TabBar页签宽度由内容(文字/图标)实际长度决定,非强制均分 - 支持滚动:当所有页签总宽度超出
TabBar容器宽度时,可横向滑动显示隐藏页签 - 布局灵活:适配大量页签场景,内容展示更完整
适用场景
- 应用顶部分类导航(如新闻频道、商品分类,页签数量多且不固定)
- 页签文字长度差异大、需自适应宽度的场景
- 动态增减页签、内容可扩展的导航界面
代码配置
Tabs(){
// TabContent 定义...
}.barMode(BarMode.Scrollable) // 配置可滚动模式
完整代码
// xxx.ets@Entry
@Component
struct TabsExample {
@State text: string = '文本';
@State barMode: BarMode = BarMode.Fixed;
build() {
Column() {
// 文本控制按钮
Row() {
Button('文本增加 ').width('47%').height(50).backgroundColor(Color.Blue).fontColor(Color.White).borderRadius(12).onClick(() => {
this.text += '文本增加';
}).margin({ right: '6%', bottom: 12 })
Button('文本重置').width('47%').height(50).backgroundColor(Color.Orange).fontColor(Color.White).borderRadius(12).onClick(() => {
this.text = '文本';
}).margin({ bottom: 12 })
}
// 模式切换按钮
Row() {
Button('Fixed 固定模式').width('47%').height(50).backgroundColor('#0088ff').fontColor(Color.White).borderRadius(12).onClick(() => {
this.barMode = BarMode.Fixed;
}).margin({ right: '6%', bottom: 12 })
Button('Scrollable 滚动模式').width('47%').height(50).backgroundColor('#33bb33').fontColor(Color.White).borderRadius(12).onClick(() => {
this.barMode = BarMode.Scrollable;
}).margin({ bottom: 12 })
}
// 核心 Tabs 组件
Tabs() {
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Pink)
}.tabBar(`${this.text} 页面 1`)
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Green)
}.tabBar(`${this.text} 页面 2`)
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Blue)
}.tabBar(`${this.text} 页面 3`)
}.height('60%').backgroundColor(0xf1f3f5).barMode(this.barMode).scrollable(true).animationDuration(300)
}.width('100%').height('100%').padding(24)
}
}


