TabComponent.ets 2.07 KB
import { TabChatComponent } from './TabChatComponent'
import { TabInfoComponent } from './TabInfoComponent'
import { TabLiveComponent } from './TabLiveComponent'

@Component
export struct TabComponent {
  @Prop @Watch('changeToChart') changeToTab: number
  @State fontColor: string = '#999999'
  @State selectedFontColor: string = '#222222'
  @State currentIndex: number = 0
  private controller: TabsController = new TabsController()
  @Prop tabs: string[] = []

  aboutToAppear(): void {

  }

  /**
   * 评论切换到大家聊
   */
  changeToChart() {
    const index = this.tabs.findIndex(item => item === '大家聊')
    if (index !== -1) {
      this.controller.changeIndex(index)
    }
  }

  build() {
    Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
      ForEach(this.tabs, (item: string, index: number) => {
        TabContent() {
          if ('简介' === item) {
            TabInfoComponent()
          } else if ('直播间' === item) {
            TabLiveComponent()
          } else if ('大家聊' === item) {
            TabChatComponent()
          }
        }.tabBar(this.tabBuilder(index, item))
        .backgroundColor('#F5F5F5')
      }, (item: string, index: number) => {
        return item + index
      })
    }
    .layoutWeight(1)
    .vertical(false)
    .barMode(BarMode.Fixed)
    .barWidth(70 * this.tabs.length)
    .barHeight(48)
    .animationDuration(100)
    .onChange((index: number) => {
      this.currentIndex = index
    })
    .backgroundColor(Color.White)
  }

  @Builder
  tabBuilder(index: number, name: string) {
    Column() {
      Text(name)
        .margin({ top: 6 })
        .fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
        .fontSize('18fp')
        .fontWeight(this.currentIndex === index ? 600 : 400)
      Divider()
        .strokeWidth(2)
        .margin({ top: 6 })
        .width(15)
        .color('#CB0000')
        .visibility(this.currentIndex === index ? Visibility.Visible : Visibility.Hidden)
    }.width('100%')
  }

  aboutToDisappear(): void {
  }
}