一、功能简介
本篇教你如何在多个页面间进行跳转与返回,配合顶部导航栏,实现简单的页面导航逻辑。适用于多页应用的基础构建。
二、页面结构
entry/
├── src/
│ └── main/
│ └── ets/
│ └── pages/
│ ├── Index.ets // 首页
│ └── Detail.ets // 详情页
├── config.json
└── app.json5
三、代码演示
Index.ets
@Entry
@Component
struct Index {
@State message: string = '欢迎来到首页'
build() {
Column() {
Text(this.message)
.fontSize(22)
.fontColor(Color.Black)
.margin(20)
Button('跳转到详情页')
.margin({ top: 20 })
.onClick(() => {
router.pushUrl({ url: 'pages/Detail' })
})
}
.width('100%')
.height('100%')
.padding(20)
}
}
Detail.ets
@Component
struct Detail {
build() {
Column() {
Text('这里是详情页')
.fontSize(22)
.fontColor(Color.Black)
.margin(20)
Button('返回首页')
.margin({ top: 20 })
.onClick(() => {
router.back()
})
}
.width('100%')
.height('100%')
.padding(20)
}
}
app.json5
注册页面
{
"pages": [
"pages/Index",
"pages/Detail"
],
"mainPage": "pages/Index"
}
四、运行效果
-
启动应用显示首页文字与按钮:
欢迎来到首页 [跳转到详情页]
-
点击按钮跳转至详情页:
这里是详情页 [返回首页]
-
点击返回按钮,回到首页。
五、常见易错点
易错点 | 表现 | 排查建议 |
---|---|---|
页面跳转失败 | 报错找不到页面 | 检查 app.json5 中是否注册 pages/Detail 路径 |
router 未导入 | 报错找不到 router | 不需要手动导入,确保使用 router.pushUrl() 而非 push() |
@Entry 重复使用 | 报错多个入口组件 | 只能在一个页面使用 @Entry ,其他页仅需 @Component |