鸿蒙应用开发:Navigation使用方法
·
了解Navigation
Navigation组件适用于模块内页面切换,可以通过组件级路由能力实现更加自然流畅的转场体验。
Navigation包含首页内容和非首页内容,首页中主要实现导航栏的功能,非首页主要显示跳转后的内容。根据效果图,可以观察到通过结构化数据构建页面小节中的知识地图页为首页,而知识地图详情页为非首页。
在知识地图页面(里面包含一个NarBarItem组件):
import { Section, KnowledgeMapContent } from '../view/KnowledgeMapContent';
export struct KnowledgeMap {
@Provide('knowledgeMapPageStack') knowledgeMapPageStack: NavPathStack = new NavPathStack();
@State currentNavBarIndex: number = -1;
@Builder
PageMap(name: string) {
//name是你给这个页面起的“路由名称”或“导航标签”,假如你定义为home只要你在跳转时也写pushPathByName('home'),它就能正确跳转。
if (name === 'KnowledgeMapContent') {
KnowledgeMapContent({ section: this.sections[this.currentNavBarIndex] });
}
}
build() {
Navigation(this.knowledgeMapPageStack) {
Scroll(){
Column(){
List({space:12}){
ForEach(this.navBarList,(item:NavBarItemType,index:number) => {
ListItem(){
NavBarItem({navBarItem:item,currentNavBarIndex:this.currentNavBarIndex})
}
.width('100%)
},(item:NavBarItemType):string => item.title)
}
}
...
}
...
}
.hideTitleBar(true)
.navDestination(this.PageMap)
.mode(NavigationMode.Stack)
}
}
在NavBarItem组件:
@Component
export struct NavBarItem {
@Consume('knowledgeMapPageStack') knowledgeMapPageStack: NavPathStack;
@Link currentNavBarIndex: number;
...
build() {
Row() {
...
}
...
.backgroundColor(
this.currentNavBarIndex === Number(this.navBarItem.order) - 1 ?
'#1A0A59F7' :
Color.Transparent
)
.onClick(() => {
const index = Number(this.navBarItem.order) - 1;
this.currentNavBarIndex = index;
this.knowledgeMapPageStack.replacePath({ name: 'KnowledgeMapContent' });
})
}
}
在KnowledgeMapContent组件中:(知识地图要跳转到这个只是地图详情页)
export struct KnowledgeMapContent {
...
build() {
NavDestination() {
Scroll(this.scroller) {
...
}
...
}
.hideTitleBar(true)
}
}
基于 Navigation 组件的跳转(推荐用于复杂应用)
1. navPathStack.pushPathByName(name)
- 功能:将指定名称的页面压入导航栈,保留当前页。
- 特点:支持传参,可返回。
- 适用场景:内部页面跳转,如“首页 → 文章详情”。
- 示例:
this.navStack.pushPathByName('articleDetail', { id: 1 });
2. navPathStack.replacePathByName(name)
- 功能:用新页面替换当前页面。
- 特点:原页面销毁,无法返回。
- 示例:
this.navStack.replacePathByName('profile');
3. navPathStack.pop()
- 功能:返回上一页(出栈)。
- 特点:可带回返回值。
- 示例:
this.navStack.pop();
4. navPathStack.clear()
- 功能:清空导航栈(较少使用)。
更多推荐


所有评论(0)