自定义tab,子页面无法监听到tab切换,见如下代码《TestTabsPage.ets》
@Builder
function JhkPageMain(index: number) {
pageMain({currentIndex: index})
}
@Component
struct pageMain {
@Prop @Watch('onCountUpdated') currentIndex: number = 0;
@State total: number = 0;
@State txt: string = '默认显示';
// @Watch 回调
onCountUpdated(propName: string): void {
console.log('输出:currentIndex',this.currentIndex)
console.log('输出:total',this.total)
if (this.total != this.currentIndex) {
this.txt = 'pageMain组件隐藏了'
}else{
this.txt = 'pageMain组件重新显示了'
}
}
build() {
Text(this.txt)
}
}
@Builder
function JhkPageNews(index: number) {
pageNews()
}
@Component
struct pageNews {
build() {
Column().width('100%').height('100%').backgroundColor('#ff0033cb')
}
}
@Builder
function JhkPageMine(index: number) {
pageMine()
}
@Component
struct pageMine {
build() {
Column().width('100%').height('100%').backgroundColor('#ffcb0018')
}
}
@Builder
export function JhkTestTabsPage() {
BuildPage()
}
@Component
struct BuildPage {
contentBuilderList: WrappedBuilder<[number]>[] =
[
wrapBuilder(JhkPageMain),
wrapBuilder(JhkPageNews),
wrapBuilder(JhkPageMine),
];
build() {
tabsBuildPage({
contentBuilderList: this.contentBuilderList
})
}
}
@Component
struct tabsBuildPage {
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
@State contentBuilderList: WrappedBuilder<[number]>[] = []
private controller: TabsController = new TabsController()
@Builder tabBuilder(index: number, name: string) {
Column() {
Text(name)
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(16)
.fontWeight(this.currentIndex === index ? 500 : 400)
.lineHeight(22)
.margin({ top: 17, bottom: 7 })
Divider()
.strokeWidth(2)
.color('#007DFF')
.opacity(this.currentIndex === index ? 1 : 0)
}.width('100%')
}
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, index: this.currentIndex, controller: this.controller }) {
ForEach(this.contentBuilderList, (itemBuilder: WrappedBuilder<[number]>, index: number) => {
TabContent() {
itemBuilder.builder(index);
}
.tabBar(this.tabBuilder(index, `${index}`))
})
}
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(360)
.barHeight(56)
.animationDuration(400)
.onChange((index: number) => {
this.currentIndex = index
})
.width(360)
.height(296)
.margin({ top: 52 })
.backgroundColor('#F1F3F5')
}.width('100%')
}
}
请参考此demo: