HarmonyOS tab组件的页签该怎么实现?

如题:HarmonyOS tab组件的页签该怎么实现?

阅读 627
1 个回答

参考如下示例,点击页签,页签移动至最左端:

@Entry
@Component
struct Index {
  @State tabArray: Array<number> = [0,1,2,3,4,5,6]
  @State focusIndex: number = 0
  private controller: TabsController = new TabsController()
  scrollerForList: Scroller = new Scroller()

  // 单独的页签
  @Builder
  Tab(tabName: string, tabItem: number, tabIndex: number) {
    Column({ space: 20 }) {
      Text(tabName).fontSize(18)
    }
    .width(100)
    .height(30)
    .borderRadius({ topLeft: 10, topRight: 10 })
    .onClick(() => {
      this.controller.changeIndex(tabIndex)
      this.focusIndex = tabIndex
    })
    .backgroundColor(tabIndex === this.focusIndex ? "#ffffffff" : "#ffb7b7b7")
  }

  build() {
    Column() {
      // 页签
      Row() {
        List({ scroller: this.scrollerForList }) {
          ForEach(this.tabArray, (item: number, index: number) => {
            ListItem() {
              this.Tab("页" + item, item, index)
            }
          })
        }
        .listDirection(Axis.Horizontal)
        .scrollBar(BarState.Off)
      }
      .height(30)
      .justifyContent(FlexAlign.Start)
      .width('100%')
      .backgroundColor("#ffb7b7b7")

      //tabs
      Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
        ForEach(this.tabArray, (item: number, index: number) => {
          TabContent() {
            Text('我是页面 ' + item + " 的内容")
              .height(300)
              .width('100%')
              .fontSize(30)
          }
          .backgroundColor(Color.Blue)
        })
      }
      .barMode(BarMode.Scrollable)
      .barHeight(0)
      .animationDuration(100)
      .onChange((index: number) => {
        this.focusIndex = index
        // 使用scroller实现上下联动,具体滚动效果根据业务需要自行设计,以下为滚动示例
        this.scrollerForList.scrollToIndex(index,true)
      })
    }
    .alignItems(HorizontalAlign.Start)
    .width('100%')
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进