HarmonyOS鸿蒙Next中Navigation子页面如何注册?
HarmonyOS鸿蒙Next中Navigation子页面如何注册?
我项目中使用了Navigation,代码如下:
build() {
Navigation(this.mainPageStack){
Flex({
direction: FlexDirection.Column
}){
Tabs({index: this.currentIndex}){
//页面
xxxx....
}.scrollable(false)
.backgroundColor(Color.Black)
.layoutWeight(1)
.barHeight(0)
.onChange((index) => {
this.currentIndex = index;
})
CustomTabBar({currentIndex: this.currentIndex, clickTabBarIndex: (index: TabBarType) => {
this.currentIndex = index;
})
}
.width(CommonConstants.FULL_PERCENT)
.height(CommonConstants.FULL_PERCENT)
}
.mode(NavigationMode.Stack)
.navDestination(this.PageMap)
.hideToolBar(true)
}
// 注册方式来源 https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-navigation-navigation
@Builder
PageMap(name: string) {
if(name === RouterConstants.User_Protocol_Page){
UserProtocolPage()
} else if(name === RouterConstants.User_Privacy_Page){
UserPrivacyPage()
} else if(name === RouterConstants.About_Us_Page){
AboutUs()
} else if(name === RouterConstants.Login_Page){
LoginPage()
} else if(name === 'xyc'){
// PageOneE()
}
}
页面的注册方式,就是参考 https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/arkts-navigation-navigation 中的示例写的。但是我有个疑问,如果有几十个子页面,都这样写的话,是不是不够优雅?也没找到其他方式,我是没有找到,请教各位,有其他的方式注册子页面吗?
更多关于HarmonyOS鸿蒙Next中Navigation子页面如何注册?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
【解决方案】
从API12开始,Navigation支持使用系统路由表的方式进行路由注册。需要配置route_map.json文件,在触发路由跳转时,应用只需要通过NavPathStack提供的路由方法,传入需要路由的页面配置名称,此时系统会自动完成路由模块的动态加载、页面组件构建,并完成路由跳转,从而实现了开发层面的模块解耦。示例代码参考:Navigation系统路由。
【总结】
Navigation子页面注册方式有设置navDestination属性和系统路由表两种,使用后者时需要注意去掉navDestination属性设置,否则不会跳转到路由表中配置的页面。
更多关于HarmonyOS鸿蒙Next中Navigation子页面如何注册?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中,Navigation子页面通过router.pushUrl()
方法导航时自动注册。需先在resources/base/profile/main_pages.json
中配置路由路径。示例代码如下:
// 子页面配置
{
"src": "pages/SubPage"
}
// 父页面导航
import router from '@ohos.router'
router.pushUrl({
url: 'pages/SubPage'
})
子页面无需单独注册,路由系统会自动管理页面栈。页面路径需与配置文件严格匹配。
在HarmonyOS Next中,Navigation的子页面注册确实可以通过更优雅的方式实现。针对您的情况,可以考虑以下优化方案:
- 使用Map对象管理页面路由:
private pageMap = new Map<string, Function>([
[RouterConstants.User_Protocol_Page, () => UserProtocolPage()],
[RouterConstants.User_Privacy_Page, () => UserPrivacyPage()],
// 其他页面...
]);
@Builder
PageMap(name: string) {
const pageBuilder = this.pageMap.get(name);
pageBuilder?.();
}
- 或者使用switch语句:
@Builder
PageMap(name: string) {
switch(name) {
case RouterConstants.User_Protocol_Page:
UserProtocolPage();
break;
case RouterConstants.User_Privacy_Page:
UserPrivacyPage();
break;
// 其他case...
default:
break;
}
}
这些方式都能有效减少if-else嵌套,提高代码可读性和维护性。Map方案更适合大量页面的场景,便于集中管理路由映射关系。