入门版 鸿蒙 组件导航 (Navigation)
注意:使用 DevEco Studio 运行本案例,要使用模拟器,千万不要用预览器,预览器看看 Navigation 布局还是可以的
- 效果:点击首页(Index)跳转到页面(MainPage)
- 先写 Index 和 MainPage 这两个页面
- 路由相关配置
Index 和 MainPage 两个页面,点击这个两个页面可以互相跳转
ts
// src/main/ets/pages/Index.ets
@Entry
@Component
struct Index {
// 创建导航路径栈实例,用于管理页面跳转历史
pageStack: NavPathStack = new NavPathStack()
build() {
// 使用Navigation组件作为导航容器,传入pageStack管理路由
Navigation(this.pageStack) {
Column() {
}
.width('100%')
.height('100%')
.backgroundColor(Color.Blue)
.onClick(() => {
// 击时压入名为"MainPage"的新页面到路径栈
this.pageStack.pushPathByName("MainPage", null);
})
}
}
}
ts
// src/main/ets/pages/MainPage.ets
// 跳转页面入口函数
@Builder
export function MainPageBuilder() {
MainPage()
}
@Component
struct MainPage {
pageStack: NavPathStack = new NavPathStack()
build() {
// 定义导航目标页面的容器
NavDestination() {
}
.width('100%')
.height('100%')
.backgroundColor(Color.Brown)
.title('MainPage')
.onClick(() => {
// 清空导航路径栈(用于返回首页)
this.pageStack.clear()
})
// 页面就绪回调onReady
.onReady((context: NavDestinationContext) => {
// 从上下文中获取路径栈实例(需确保与父组件共享同一个实例)
this.pageStack = context.pathStack
})
}
}
路由相关的配置
在跳转目标模块的配置文件 module.json5 添加路由表配置
ts
// src/main/module.json5
{
"module" : {
"routerMap": "$profile:route_map"
}
}
添加完路由配置文件地址后,需要在工程 resources/base/profile 中创建 route_map.json 文件
ts
// src/main/resources/base/profile/router_map.json
{
"routerMap": [
{
"name": "MainPage",
"pageSourceFile": "src/main/ets/pages/MainPage.ets",
"buildFunction": "MainPageBuilder",
"data": {
"description": "this is MainPage"
}
}
]
}
ts
// src/main/resources/base/profile/main_pages.json
{
"src": [
"pages/Index"
]
}