/** * 第 10 章配套代码 · 主框架页(5 Tab + 路由切换) * * 文件位置:shared/src/commonMain/kotlin/com/example/xhs/pages/MainPage.kt * * 这是「迷你小红书」的入口 Pager。 * 所有 Tab 共享 1 个 Pager,按 currentTab 切换内容区,避免每次跳转重建。 * * 涉及知识点: * - 跨页面共享状态(TabStore / ThemeStore / UserStore) * - ViewBuilder 抽组件(BottomTabBar) * - 条件渲染(when 切换 Tab 内容) */ package com.example.xhs.pages import com.example.xhs.components.BottomTabBar import com.example.xhs.store.TabStore import com.example.xhs.store.ThemeStore import com.tencent.kuikly.core.annotations.Page import com.tencent.kuikly.core.base.Color import com.tencent.kuikly.core.base.ViewBuilder import com.tencent.kuikly.core.pager.Pager import com.tencent.kuikly.core.views.View @Page("MainPage") internal class MainPage : Pager() { // 复用各 Tab 页面的实例(避免每次切换都新建) private val homePage by lazy { HomePage() } private val explorePage by lazy { ExplorePage() } private val publishPage by lazy { PublishPage() } private val messagePage by lazy { MessagePage() } private val profilePage by lazy { ProfilePage() } override fun body(): ViewBuilder { return { attr { backgroundColor( if (ThemeStore.darkMode) Color(0xFF121212L) else Color(0xFFF5F5F7L) ) } // ─── 主内容区 ───── View { attr { flex(1f) } when (TabStore.currentTab) { "home" -> homePage.body().invoke(this) "explore" -> explorePage.body().invoke(this) "publish" -> publishPage.body().invoke(this) "message" -> messagePage.body().invoke(this) "profile" -> profilePage.body().invoke(this) } } // ─── 底部 Tab 栏 ───── BottomTabBar( current = TabStore.currentTab, onSelect = { id -> TabStore.currentTab = id }, ).invoke(this) } } } // ─── 跨页面共享 Tab 状态 ─────────────────────── package com.example.xhs.store import com.tencent.kuikly.core.reactive.handler.observable object TabStore { var currentTab by observable("home") // home / explore / publish / message / profile } object ThemeStore { var darkMode by observable(false) fun toggle() { darkMode = !darkMode } }