【HarmonyOS Next开发】Navigation使用

简介: Navigation是路由容器组件,包括单栏(Stack)、分栏(Split)和自适应(Auto)三种显示模式。适用于模块内和跨模块的路由切换。在页面跳转时,应该使用页面路由router,在页面内的页面跳转时,建议使用Navigation达到更好的转场动效场景。

简介

Navigation是路由容器组件,包括单栏(Stack)、分栏(Split)和自适应(Auto)三种显示模式。适用于模块内和跨模块的路由切换。

在页面跳转时,应该使用页面路由router,在页面内的页面跳转时,建议使用Navigation达到更好的转场动效场景。

UI框架

1.png

显示模式

通过mode属性来定义

Navigation() {
  ...
}
.mode(NavigationMode.Auto)
AI 代码解读

自适应(Auto)模式

组件默认的模式,当页面宽度大于等于一定阈值( API version 9及以前:520vp,API version 10及以后:600vp )时,Navigation组件采用分栏模式,反之采用单栏模式。

单栏(Stack)模式

2.png

分栏(Split)模式

3.png

标题栏模式

通过titleMode属性设置标题栏模式,分别有Mini模式和Full模式

  • Mini模式

4.png

  • Full模式

5.png

菜单栏

通过menus属性进行设置。支持Array和CustomBuilder两种类型。

注意:使用Array时,竖屏最多支持3个图标,横屏最多支持5个图标

@Entry
@Component
struct Index {
  ToolTmp: NavigationMenuItem = {
    value: "",
    icon: "resources/base/media/startIcon.png",
    action: () => {

    }
  }

  build() {
    Column() {
      Navigation() {

      }
      .title("主标题")
      .titleMode(NavigationTitleMode.Full)
      .menus([
        this.ToolTmp,
        this.ToolTmp,
        this.ToolTmp
      ])
    }
    .width("100%")
    .height("100%")
    .backgroundColor('#F1F3F5')
  }
}
AI 代码解读

工具栏

工具栏位于Navigation组件的底部,通过toolbarConfiguration属性进行设置。

@Entry
@Component
struct Index {
  ToolTmp: NavigationMenuItem = {
    value: "",
    icon: "resources/base/media/startIcon.png",
    action: () => {

    }
  }
  Toolbar: ToolbarItem = {
    value: "test",
    icon: $r('app.media.app_icon'),
    action: () => {
    }
  }

  build() {
    Column() {
      Navigation() {

      }
      .title("主标题")
      .titleMode(NavigationTitleMode.Full)
      .menus([
        this.ToolTmp,
        this.ToolTmp,
        this.ToolTmp
      ])
      .toolbarConfiguration([
        this.Toolbar,
        this.Toolbar,
        this.Toolbar
      ])
    }
    .width("100%")
    .height("100%")
    .backgroundColor('#F1F3F5')
  }
}
AI 代码解读

路由操作

Navigation路由相关的操作都是基于页面栈NavPathStack对象。主要涉及页面跳转、页面返回、页面替换、页面删除、参数获取、路由拦截等功能。

定义一个NavPathStack对象:pageStack: NavPathStack = new NavPathStack()

9.png

页面跳转

  • 普通跳转,通过页面的name去跳转
this.pageStack.pushPathByName("PageOne", "PageOne Param")
AI 代码解读

  • 带返回回调的跳转,跳转时添加onPop回调,能在页面出栈时获取返回信息,并进行处理。
this.pageStack.pushPathByName('PageOne', "PageOne Param", (popInfo) => {
console.log('Pop page name is: ' + popInfo.info.name + ', result: ' + JSON.stringify(popInfo.result))
});
AI 代码解读

  • 带错误码的跳转,跳转结束会触发异步回调,返回错误码信息。
this.pageStack.pushDestinationByName('PageOne', "PageOne Param")
.catch((error: BusinessError) => {
    console.error(`Push destination failed, error code = ${error.code}, error.message = ${error.message}.`);
}).then(() => {
console.error('Push destination succeed.');
});
AI 代码解读

页面返回

// 返回到上一页
this.pageStack.pop()
// 返回到上一个PageOne页面
this.pageStack.popToName("PageOne")
// 返回到索引为1的页面
this.pageStack.popToIndex(1)
// 返回到根首页(清除栈中所有页面)
this.pageStack.clear()
AI 代码解读

页面替换

this.pageStack.replacePathByName("PageOne", "PageOne Param")
AI 代码解读

页面删除

// 删除栈中name为PageOne的所有页面
this.pageStack.removeByName("PageOne")
// 删除指定索引的页面
this.pageStack.removeByIndexes([1,3,5])
AI 代码解读

页面参数获取

// 获取栈中所有页面name集合
this.pageStack.getAllPathName()
// 获取索引为1的页面参数
this.pageStack.getParamByIndex(1)
// 获取PageOne页面的参数
this.pageStack.getParamByName("PageOne")
// 获取PageOne页面的索引集合
this.pageStack.getIndexByName("PageOne")
AI 代码解读

页面转场

Navigation默认提供了页面切换的转场动画,通过页面栈操作时,会触发不同的转场效果(Dialog类型的页面默认无转场动画),Navigation也提供了关闭系统转场、自定义转场以及共享元素转场的能力。

关闭转场

  • 全局关闭
pageStack: NavPathStack = new NavPathStack()

aboutToAppear(): void {
  this.pageStack.disableAnimation(true)
}
AI 代码解读

  • 单次关闭
pageStack: NavPathStack = new NavPathStack()

this.pageStack.pushPath({ name: "PageOne" }, false)
this.pageStack.pop(false)
AI 代码解读

子页面显示类型

  • 标准类型(NavDestinationMode.STANDARD),生命周期跟随其在NavPathStack页面栈中的位置变化而改变。
  • 弹窗类型(NavDestinationMode.DIALOG),显示和消失时不会影响下层标准类型的NavDestination的显示和生命周期,两者可以同时显示。

子页面生命周期(NavDestination)

6.png

  • aboutToAppear:在创建自定义组件后,执行其build()函数之前执行(NavDestination创建之前),允许在该方法中改变状态变量,更改将在后续执行build()函数中生效。
  • onWillAppear:NavDestination创建后,挂载到组件树之前执行,在该方法中更改状态变量会在当前帧显示生效。
  • onAppear:通用生命周期事件,NavDestination组件挂载到组件树时执行。
  • onWillShow:NavDestination组件布局显示之前执行,此时页面不可见(应用切换到前台不会触发)。
  • onShown:NavDestination组件布局显示之后执行,此时页面已完成布局。
  • onWillHide:NavDestination组件触发隐藏之前执行(应用切换到后台不会触发)。
  • onHidden:NavDestination组件触发隐藏后执行(非栈顶页面push进栈,栈顶页面pop出栈或应用切换到后台)。
  • onWillDisappear:NavDestination组件即将销毁之前执行,如果有转场动画,会在动画前触发(栈顶页面pop出栈)。
  • onDisappear:通用生命周期事件,NavDestination组件从组件树上卸载销毁时执行。
  • aboutToDisappear:自定义组件析构销毁之前执行,不允许在该方法中改变状态变量。

使用案例

实现简单的登录界面跳转。

7.gif

项目目录

8.png

Index

import { component_1 } from '../Components/component_1';
import { component_2 } from '../Components/component_2';
import { LoginParam } from '../Models/LoginParam';

@Entry
@Component
struct Index {
  @Provide("pageNavigation") pageNav: NavPathStack = new NavPathStack();

  @Builder
  PageMap(path: string) {
    if (path == "component_1") {
      component_1()
    }
    if (path == "component_2") {
      component_2()
    }

  }

  build() {
    Column() {
      Navigation(this.pageNav) {
        Button("直接跳转component_1界面(不带参数)")
          .width("80%")
          .margin({ bottom: 20 })
          .onClick(() => {
            this.pageNav.pushPathByName("component_1", "")
          })
        Button("直接跳转component_1界面(带参数)")
          .width("80%")
          .margin({ bottom: 20 })
          .onClick(() => {
            let login: LoginParam = new LoginParam("张三", "1234567");
            this.pageNav.pushPathByName("component_1", login)
          })
      }
      .title("主页")
      .titleMode(NavigationTitleMode.Full)
      .mode(NavigationMode.Auto)
      .navDestination(this.PageMap)
    }
    .height('100%')
    .width('100%')
  }
}
AI 代码解读

component_1

import { LoginParam } from '../Models/LoginParam';
import { JSON } from '@kit.ArkTS';

@Component
export struct component_1 {
  @Consume("pageNavigation") pageNav: NavPathStack;
  @State login: LoginParam = new LoginParam("", "")

  build() {
    Column() {
      NavDestination() {
        Row() {
          Text("账户:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
          TextInput({ text: this.login.Name, placeholder: "请输入账户" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .onChange((value) => {
              this.login.Name = value
            })
        }
        .width("100%")

        Row() {
          Text("密码:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
          TextInput({ text: this.login.Password, placeholder: "请输入密码" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .type(InputType.Password)
            .onChange((value) => {
              this.login.Password = value
            })
        }
        .width("100%")
        .margin({ top: 20 })

        Grid() {
          GridItem() {
            Button("注册")
              .width("100%")
              .backgroundColor("#f1f2f3")
              .fontColor("#007dfe")
              .onClick(() => {
                this.pageNav.pushPathByName("component_2", this.login.Name, (popInfo) => {
                  if (popInfo.result != null) {
                    let popLogin: LoginParam = popInfo.result as LoginParam;
                    if (popLogin == null) {
                      return;
                    }
                    this.login = popLogin;
                  }
                });
              })

          }
          .width("50%")
          .padding({ right: 10, left: 10 })

          GridItem() {
            Button("登录")
              .width("100%")
              .onClick(() => {
                console.log(JSON.stringify(this.login))
              })
          }
          .width("50%")
          .padding({ right: 10, left: 10 })
        }
        .rowsTemplate("1tf 1tf")
        .margin({ top: 10 })
        .width("100%")
        .height(60)
      }
      .title("登录")
      .mode(NavDestinationMode.STANDARD)
      .onWillShow(() => {
        let tempPara: LoginParam[] | string[] = this.pageNav.getParamByName("component_1") as LoginParam[] | string[]
        if (tempPara.length == 0 || tempPara[0] == "") {
          return;
        }
        this.login = tempPara[0] as LoginParam
      })
    }
    .width("100%")
    .height("100%")

  }
}
AI 代码解读

component_2

import { LoginParam } from '../Models/LoginParam'
import { promptAction } from '@kit.ArkUI';

@Component
export struct component_2 {
  @Consume("pageNavigation") pageNav: NavPathStack;
  @State login: LoginParam = new LoginParam("", "");
  @State tempPassword: string = "";

  build() {
    Column() {
      NavDestination() {
        Row() {
          Text("账户:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
            .width(40)
          TextInput({ text: this.login.Name, placeholder: "请输入账户" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .onChange((value) => {
              this.login.Name = value
            })
        }
        .width("100%")

        Row() {
          Text("密码:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
            .width(40)
          TextInput({ text: this.login.Password, placeholder: "请输入密码" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .type(InputType.Password)
            .onChange((value) => {
              this.login.Password = value
            })
        }
        .width("100%")
        .margin({ top: 20 })

        Row() {
          Text("确认密码:")
            .fontSize(16)
            .margin({ left: 10, right: 10 })
            .width(40)
          TextInput({ text: $$this.tempPassword, placeholder: "请再次输入密码" })
            .layoutWeight(1)
            .margin({ right: 10 })
            .type(InputType.Password)
            .onChange((value) => {
              this.tempPassword = value
            })
        }
        .width("100%")
        .margin({ top: 20 })


        Column() {
          Button("注册")
            .width("100%")
            .onClick(() => {
              if (this.tempPassword != "" && this.tempPassword === this.login.Password && this.login.Name != "") {
                this.pageNav.pop(this.login)
              } else {
                promptAction.showDialog({
                  title: "提示",
                  message: "注册失败,密码不一致或账户为空",
                  buttons: [
                    {
                      text: "确认",
                      color: "#000"
                    }
                  ]
                })
              }
            })
        }
        .width("100%")
        .margin({ top: 20 })
        .padding({ right: 10, left: 10 })
      }
      .title("注册")
      .mode(NavDestinationMode.STANDARD)
      .onWillShow(() => {
        let names: string[] = this.pageNav.getParamByName("component_2") as string[];
        if (names == null || names.length === 0) {
          return;
        }
        this.login.Name = names[0]
      })
    }
    .width("100%")
    .height("100%")

  }
}
AI 代码解读

LoginParam

@Observed
export class LoginParam {
  Name: string = "";
  Password: string = "";

  constructor(name: string, password: string) {
    this.Name = name;
    this.Password = password;
  }
}
AI 代码解读

相关文章
|
28天前
|
鸿蒙开发:资讯项目实战之项目初始化搭建
目前来说,我们的资讯项目只是往前迈了很小的一步,仅仅实现了项目创建,步虽小,但概念性的知识很多,这也是这个项目的初衷,让大家不仅仅可以掌握日常的技术开发,也能让大家理解实际的项目开发知识。
鸿蒙开发:资讯项目实战之项目初始化搭建
鸿蒙开发:基于最新API,如何实现组件化运行
手动只是让大家了解切换的原理,在实际开发中,可不推荐手动,下篇文章,我们将通过脚本或者插件,快速实现组件化模块之间的切换,实现独立运行,敬请期待!
鸿蒙开发:基于最新API,如何实现组件化运行
鸿蒙5开发宝藏案例分享---优化应用时延问题
鸿蒙性能优化指南来了!从UI渲染到数据库操作,6大实战案例助你提升应用流畅度。布局层级优化、数据加载并发、数据库查询提速、相机资源延迟释放、手势识别灵敏调整及转场动画精调,全面覆盖性能痛点。附赠性能自检清单,帮助开发者高效定位问题,让应用运行如飞!来自华为官方文档的精华内容,建议收藏并反复研读,共同探讨更多优化技巧。
鸿蒙5开发宝藏案例分享---Swiper组件性能优化实战
本文分享了鸿蒙系统中Swiper组件的性能优化技巧,包括:1) 使用`LazyForEach`替代`ForEach`实现懒加载,显著降低内存占用;2) 通过`cachedCount`精准控制缓存数量,平衡流畅度与内存消耗;3) 利用`onAnimationStart`在抛滑时提前加载资源,提升构建效率;4) 添加`@Reusable`装饰器复用组件实例,减少创建开销。实际应用后,图库页帧率从45fps提升至58fps,效果显著。适合处理复杂列表或轮播场景,欢迎交流经验!
HarmonyOS Next快速入门:了解项目工程目录结构
本教程旨在帮助开发者快速上手HarmonyOS应用开发,涵盖从环境搭建到工程创建的全流程。通过DevEco Studio创建首个项目时,选择“Application”与“Empty Ability”,配置项目名称、包名、保存路径等关键信息后完成创建。代码示例展示了基本UI组件的使用,如`Hello World`文本显示与交互逻辑。此外,详细解析了工程目录结构,包括AppScope自动生成规则、主模块(entry)的功能划分、依赖配置文件(oh-package.json5)的作用,以及app.json5中包名、版本号等全局配置项的含义。
70 5
|
22天前
|
HarmonyOS Next快速入门:通用属性
本教程以《HarmonyOS Next快速入门》为基础,涵盖应用开发核心技能。通过代码实例讲解尺寸、位置、布局约束、Flex布局、边框、背景及图像效果等属性设置方法。如`.width()`调整宽度,`.align()`设定对齐方式,`.border()`配置边框样式,以及模糊、阴影等视觉效果的实现。结合实际案例,帮助开发者掌握HarmonyOS组件属性的灵活运用,提升开发效率与用户体验。适合初学者及进阶开发者学习。
64 0
|
22天前
|
HarmonyOS Next快速入门:通用事件
本教程聚焦HarmonyOS应用开发,涵盖事件处理的核心内容。包括事件分发、触屏事件、键鼠事件、焦点事件及拖拽事件等。通过代码实例讲解点击事件、触控事件(Down/Move/Up)、获焦与失焦事件的处理逻辑,以及气泡弹窗的应用。适合开发者快速掌握HarmonyOS Next中通用事件的使用方法,提升应用交互体验。
60 0
|
22天前
|
HarmonyOS Next快速入门:Button组件
本教程摘自《HarmonyOS Next快速入门》,聚焦HarmonyOS应用开发中的Button组件。Button支持胶囊、圆形和普通三种类型,可通过子组件实现复杂功能,如嵌入图片或文字。支持自定义样式(边框弧度、文本样式、背景色等)及点击事件处理。示例代码展示了不同类型按钮的创建与交互逻辑,助开发者快速上手。适合HarmonyOS初学者及对UI组件感兴趣的开发者学习。
67 0
|
22天前
|
HarmonyOS Next快速入门:Image组件
本教程摘自《HarmonyOS Next快速入门》,专注于HarmonyOS应用开发中的Image组件使用。Image组件支持多种图片格式(如png、jpg、svg等),可渲染本地资源、网络图片、媒体库文件及PixelMap像素图。通过设置`objectFit`属性,实现不同缩放类型;利用`fillColor`属性调整矢量图颜色。示例代码涵盖本地、网络及资源图片的加载与样式设置,同时需在`module.json5`中声明网络权限以加载外部资源。适合开发者快速掌握HarmonyOS图像展示功能。
75 0
鸿蒙5开发宝藏案例分享---优化应用包体积大小问题
本文分享了鸿蒙应用包体积优化的实用技巧,包括SO库压缩、HSP动态共享包、OHPM依赖冲突解决、按需加载和扫描工具定位优化点等方法。通过具体配置示例和实战经验,如启用`compressNativeLibs`、使用共享资源包、强制统一依赖版本以及动态导入功能模块,帮助开发者显著减少包体积,提升用户体验。文中还提供了图标优化、资源混淆和无用代码剔除等补充建议,助力打造更轻量的鸿蒙应用。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等