鸿蒙:实现两个Page页面跳转

本文详细介绍了如何在鸿蒙系统中创建并实现两个页面(FirstPage和SecondPage)的跳转,包括构建页面结构、配置路由以及使用ohos.router模块进行页面间导航,包括单向和双向跳转的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果展示

这篇博文在《鸿蒙:从0到“Hello Harmony”》基础上实现两个Page页面跳转

1.构建第一个页面

第一个页面就是“Hello Harmony”,把文件名和显示内容都改一下,改成“FirstPage”,再添加一个“Next”按钮。

@Entry
@Component
struct FristPage {
  @State message1: string = "FirstPage"
  @State message2: string = 'Next'

  build() {
    Row() {
      Column() {
        Text(this.message1)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .height("10%")
          .margin({
            top: 0
          })

        Button(this.message2)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .height('5%')
          .type(ButtonType.Capsule)
          .margin({
            top: 30
          })
          .backgroundColor("#0D9FFB")
          .width('50%')
          .height('5%')
      }
      .width('100%')
    }
    .height('100%')
  }
}

在编辑窗口右上角的侧边工具栏,点击Previewer,打开预览器。第一个页面效果如下图所示:

2.构建第二个页面

1.在“entry > src > main > ets > pages”目录下,新建SecondPage.ets

同样,实现一个文本和一个Button按钮

@Entry
@Component
struct SecondPage {
  @State message1: string = 'SecondPage'
  @State message2: string = 'Back'

  build() {
    Row() {
      Column() {
        Text(this.message1)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)

        Button(this.message2)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .height('5%')
          .type(ButtonType.Capsule)
          .margin({
            top: 30
          })
          .backgroundColor("#0D9FFB")
          .width('50%')
          .height('5%')
      }
      .width('100%')
    }
    .height('100%')
  }
}

Previewer效果:

3.配置路由

配置第二个页面的路由。

在“Project”窗口,打开“entry > src > main > resources > base > profile”,

main_pages.json文件中的“src”下配置第二个页面的路由“pages/second”

代码如下:

{
  "src": [
    "pages/FirstPage",
    "pages/SecondPage"
  ]
}

4.实现页面跳转

​页面间的导航可以通过页面路由router来实现。

页面路由router根据页面url找到目标页面,从而实现跳转。

使用页面路由需要导入router模块。

(1).第一个页面跳转到第二个页面

在第一个页面中,跳转按钮绑定onClick事件,点击按钮时跳转到第二页。

FirstPage.ets”文件的代码如下:

// @ohos.router模块功能从API version 8开始支持,请使用对应匹配的SDK
import router from '@ohos.router';

@Entry
@Component
struct FristPage {
  @State message1: string = "FirstPage"
  @State message2: string = 'Next'

  build() {
    Row() {
      Column() {
        Text(this.message1)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .height("10%")
          .margin({
            top: 0
          })

        Button(this.message2)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .height('5%')
          .type(ButtonType.Capsule)
          .margin({
            top: 30
          })
          .backgroundColor("#0D9FFB")
          .width('50%')
          .height('5%')
          .onClick(() => {
            console.info(`Succeeded in clicking the 'Next' button.`)
            try {
              router.pushUrl({ url: 'pages/SecondPage' })
              console.info('Succeeded in jumping to the second page.')
            } catch (err) {
              console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`)
            }
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}

(1).第二个页面跳转到第一个页面

在第二个页面中,返回按钮绑定onClick事件,点击按钮时返回到第一页。

“SecondPage.ets”文件的示例如下:

import router from '@ohos.router';

@Entry
@Component
struct SecondPage {
  @State message1: string = 'SecondPage'
  @State message2: string = 'Back'

  build() {
    Row() {
      Column() {
        Text(this.message1)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)

        Button(this.message2)
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .height('5%')
          .type(ButtonType.Capsule)
          .margin({
            top: 30
          })
          .backgroundColor("#0D9FFB")
          .width('50%')
          .height('5%')
          .onClick(() => {
            console.info(`Succeeded in clicking the 'Next' button.`)
            try {
              router.pushUrl({ url: 'pages/FirstPage' })
              console.info('Succeeded in jumping to the second page.')
            } catch (err) {
              console.error(`Failed to jump to the second page.Code is ${err.code}, message is ${err.message}`)
            }
          })

      }
      .width('100%')
    }
    .height('100%')
  }
}

5.实现效果

如开头展示

<think>好的,我现在需要回答用户关于如何在鸿蒙5.2中实现参数传递与页面跳转的问题。首先,我得回忆一下之前用户提供的引用内容,特别是引用[1]和引用[4],因为它们提到了页面跳转和参数传递的方法。 用户提到的引用[1]中有一个示例,使用router.replaceUrl来跳转页面,并且传递了params参数。同时,引用[4]展示了如何通过泛型传递参数,可能涉及到接口的定义。不过鸿蒙系统可能使用的是不同的API,但基本思路应该是类似的。 接下来,我需要确认鸿蒙5.2的官方文档或开发指南中的页面跳转方式。通常,页面跳转可能有两种方式:带参数和不带参数。传递参数可能需要将数据放在params对象中,然后在目标页面获取这些参数。 在引用[1]中,使用了router.replaceUrl,并且指定了url和params。这可能类似于其他框架中的路由跳转。另外,引用[3]提到了使用tabs组件进行页面切换,但用户的问题是关于传参和跳转,所以可能主要参考引用[1]和[4]。 需要分步骤说明如何实现页面跳转和传参。例如,首先在源页面设置跳转并传递参数,然后在目标页面接收参数。可能涉及到路由配置,或者在目标页面的生命周期方法中获取参数。 还要考虑参数的类型和范围,比如引用[2]中提到的参数说明,可能需要注意参数的合法性和取值范围。此外,引用[4]中的示例使用了http请求传递参数,但页面跳转的参数传递可能更直接,通过路由的params对象。 可能存在两种跳转方式,比如router.pushUrl和router.replaceUrl,前者保留当前页面,后者替换当前页面。需要说明两者的区别,并给出示例代码。 另外,目标页面如何接收参数?可能需要在onPageShow或其他生命周期函数中通过router.getParams方法获取传递过来的参数。需要确保在目标页面正确获取和处理这些参数。 最后,需要检查示例代码是否符合鸿蒙5.2的语法,特别是路由相关的API是否与引用中的一致。同时,要确保参数传递的正确性和类型安全,避免出现路径错误或参数未定义的情况。 总结步骤: 1. 使用router模块的pushUrl或replaceUrl方法跳转页面,并传递params参数。 2. 在目标页面的生命周期方法中通过router.getParams获取参数。 3. 处理参数,确保类型和有效性。 现在,根据这些步骤编写具体的示例代码,并解释每个步骤的作用。同时,生成相关问题,帮助用户进一步学习。</think>### 鸿蒙5.2参数传递与页面跳转实现教程 #### 一、页面跳转基础方法 在鸿蒙5.2中,通过`router`模块实现页面跳转,支持两种核心方法: 1. **保留当前页面**:使用`router.pushUrl`跳转后可通过返回键回到原页面 2. **替换当前页面**:使用`router.replaceUrl`直接替换当前页面栈顶实例[^1] ```typescript // 示例1:带参数跳转至Detail页面(保留当前页面) import router from '@ohos.router'; let params = { id: 1001, title: '鸿蒙开发指南' }; router.pushUrl({ url: 'pages/Detail', params: params }); // 示例2:替换当前页面(无法返回) router.replaceUrl({ url: 'pages/Login', params: { from: 'HomePage' } }); ``` #### 二、参数传递规范 1. **参数类型限制** - 支持`string`/`number`/`boolean`基础类型 - 复杂对象需序列化为JSON字符串传输 - 单个参数值长度不超过8KB[^2] 2. **目标页面参数接收** 在目标页面的`onPageShow`生命周期中获取参数: ```typescript // pages/Detail.ets @Entry @Component struct DetailPage { @State message: string = '' onPageShow() { const params = router.getParams() as Record<string, string>; this.message = `ID:${params['id']}, 标题:${params['title']}`; } build() { // 页面布局 } } ``` #### 三、高级参数处理技巧 1. **类型安全验证** 推荐使用泛型接口规范参数类型[^4]: ```typescript interface PageParams { id: number; title: string; timestamp?: number; } const validateParams = (params: unknown): PageParams => { // 类型校验逻辑 } ``` 2. **跨页面通信** 通过`EventHub`实现复杂场景通信: ```typescript // 发送端 router.getEventHub().emit('dataUpdate', { newData: 2023 }); // 接收端 onPageShow() { router.getEventHub().on('dataUpdate', (data) => { console.log('收到更新:', data); }); } ``` #### 四、特殊场景处理 1. **Tab页面传参** 结合`tabs`组件时,需通过`tabContent`的`onChange`事件传递参数[^3]: ```typescript Tabs() { TabContent() { HomePage() }.tabBar('首页') TabContent() { ProfilePage() .onChange((index, params) => { if(params) handleTabParams(params) }) }.tabBar('我的') } ``` 2. **异常处理** 添加参数校验和异常捕获: ```typescript try { router.pushUrl({ url: 'pages/Payment', params: { amount: 99.9 } }); } catch (error) { console.error('路由错误:', error.code, error.message); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值