目录

SegmentButton如何设置点击回调事件

问题现象

SegmentButton如何设置点击回调事件来监听当前点击的Tab?

效果预览

背景知识

解决方案

使用@Watch装饰器设置onSegmentButtonChange回调函数,用于监听当前点击的Tab。

import {
  ItemRestriction,
  SegmentButton,
  SegmentButtonOptions,
  SegmentButtonTextItem
} from '@ohos.arkui.advanced.SegmentButton';

@Entry
@Component
struct SegmentButtonClickCallback {
  @State tabOptions: SegmentButtonOptions = SegmentButtonOptions.tab({
    buttons: [{ text: '页签按钮1' }, { text: '页签按钮2' }, {
      text: '页签按钮3'
    }] as ItemRestriction<SegmentButtonTextItem>,
    backgroundBlurStyle: BlurStyle.BACKGROUND_THICK
  });
  @State tf: boolean = true;
  @State @Watch('onSegmentButtonChange') tabSelectedIndexes: number[] = [0];

  onSegmentButtonChange() {
    this.tf = !this.tf;
    console.info(`选中按钮索引 -- ${this.tabSelectedIndexes}`);
  }

  build() {
    Row() {
      Column() {
        Column({ space: 25 }) {
          SegmentButton({
            options: this.tabOptions,
            selectedIndexes: $tabSelectedIndexes
          });
          TextInput({ text: `${this.tabSelectedIndexes}` }).enabled(this.tf);
        }.width('90%');
      }.width('100%');
    }.height('100%');
  }
}