一、背景
系统提供的Tabs目前只能居中展示,暂不支持居左显示,现有的需求是需要Tabs从左往右排列显示,考虑通过Scroll和Row组件来实现
二、实现思路
通过Scroll和Row组件用来实现一个页签,在onclick事件中通过修改索引值和Tabs组件的索引联动,实现切换效果,同时将Tabs的barHeight置为0
三、具体实现代码
@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%')}
}