加入下方官方优快云班级,得鸿蒙礼盒
本期活动时间:2025年8月1日-12月31日
问题现象
SegmentButton如何设置点击回调事件来监听当前点击的Tab?
效果预览

背景知识
- SegmentButton为分段按钮组件,包含页签类分段按钮、单选类分段按钮、多选类分段按钮。
- @Watch装饰器应用于对状态变量的监听。如果开发者需要关注某个状态变量的值是否改变,可以使用@Watch为状态变量设置回调函数。@Watch提供了状态变量的监听能力,@Watch仅能监听到可以观察到的变化。
解决方案
使用@Watch装饰器设置onSegmentButtonChange回调函数,用于监听当前点击的Tab。
import {
ItemRestriction,
SegmentButton,
SegmentButtonOptions,
SegmentButtonTextItem
} from '@ohos.arkui.advanced.SegmentButton'
@Entry
@Component
struct Index {
@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%')
}
}

被折叠的 条评论
为什么被折叠?



