【HarmonyOS NEXT】实现Tabs组件的TabBar从左到右依次排列

一、背景

系统提供的Tabs目前只能居中展示,暂不支持居左显示,现有的需求是需要Tabs从左往右排列显示,考虑通过Scroll和Row组件来实现

二、实现思路

通过Scroll和Row组件用来实现一个页签,在onclick事件中通过修改索引值和Tabs组件的索引联动,实现切换效果,同时将Tabs的barHeight置为0

三、具体实现代码

javascript 复制代码
@Entry
@Component
struct TabsComponent {
  @State tabArray: number[] = [0, 1];
  @State focusIndex: number = 0;
  private controller: TabsController = new TabsController();

  build() {
    Column() {
      // 使用自定义页签组件 
      Scroll() {
        Row() {
          ForEach(this.tabArray, (item: number, index: number) => {
            Row({ space: 20 }) {
              Text('页签' + item)
                .fontColor(index === this.focusIndex ? Color.Red : Color.Black)
                .fontWeight(index === this.focusIndex ? FontWeight.Bold : FontWeight.Normal)
            }
            .padding({ left: 10, right: 10 })
            .onClick(() => {
              this.controller.changeIndex(index);
              this.focusIndex = index;
            })
          })
        }.margin(20)
      }
      .align(Alignment.Start)
      .scrollable(ScrollDirection.Horizontal)
      .scrollBar(BarState.Off)
      .width('100%')

      //tabs组件把tabbar隐藏 
      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        ForEach(this.tabArray, (item: number, index: number) => {
          TabContent() {
            Text('我是页面 ' + item + " 的内容")
              .fontSize(30)
          }
        })
      }.barHeight(0)
    }
    .height('100%')
    .width('100%')
  }
}

四、实现效果

相关推荐
Damon小智22 分钟前
鸿蒙元服务深度实践:跨端唤醒与状态共享的设计模式
华为·设计模式·harmonyos
普中科技36 分钟前
【普中Hi3861开发攻略--基于鸿蒙OS】-- 第 31 章 WIFI 实验-华为 IoTDA 设备接入
单片机·嵌入式硬件·华为云·鸿蒙·liteos·hi3861·普中科技
广然1 小时前
跨厂商(华为 & H3C)防火墙 GRE 隧道部署
网络·华为·防火墙·h3c
Yeats_Liao1 小时前
华为开源自研AI框架昇思MindSpore应用案例:跑通Vision Transformer图像分类
人工智能·华为·transformer
星释1 小时前
鸿蒙Flutter三方库适配指南:07.插件开发
flutter·华为·harmonyos
Damon小智3 小时前
HarmonyOS 5 开发:从 Stage 模型看鸿蒙应用生命周期管理
华为·harmonyos
爱笑的眼睛113 小时前
HarmonyOS 分布式剪贴板:实现跨设备无缝数据共享的技术深度解析
华为·harmonyos
Xxtaoaooo3 小时前
【成长纪实】HarmonyOS分布式软总线原理剖析:从理论到实践的完整指南
华为·harmonyos·原理解析·成长纪实·分布式软总线
m0_685535087 小时前
汽车抬头显示(HUD)光学系统设计实例(含核心技巧解析)
华为·光学·光学设计·光学工程·镜头设计
晓oi15 小时前
基于华为设备的 OSPF+MSTP+DHCP+NAT 综合网络架构实现
网络·华为