reactive-native 路由、页面跳转

本文详细介绍如何在React Native项目中配置并使用react-navigation进行页面跳转和传参,包括安装依赖、配置路由、页面跳转及参数传递等关键步骤。

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

安装

1、在你的 React Native 项目中安装react-navigation这个包

npm install --save react-navigation

2、安装 react-native-gesture-handler

npm install --save react-native-gesture-handler

3、Link 所有的原生依赖

react-native link react-native-gesture-handler

iOS 啥都不用做,在 Android 上的安装,请确保在 MainActivity.java 上完成如下修改:

package com.reactnavigation.example;

import com.facebook.react.ReactActivity;
+ import com.facebook.react.ReactActivityDelegate;
+ import com.facebook.react.ReactRootView;
+ import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

  @Override
  protected String getMainComponentName() {
    return "Example";
  }

+  @Override
+  protected ReactActivityDelegate createReactActivityDelegate() {
+    return new ReactActivityDelegate(this, getMainComponentName()) {
+      @Override
+      protected ReactRootView createRootView() {
+       return new RNGestureHandlerEnabledRootView(MainActivity.this);
+      }
+    };
+  }
}

使用

1、建立一个navigator.js存放路由配置

import React from 'react';
import {createAppContainer, createStackNavigator, StackNavigator} from 'react-navigation';
//引入页面
import Login from '../page/Login';
import Reg from '../page/Reg';
import App from '../page/App';

const AppNavigator = createStackNavigator({
        Login: {
            screen: Login,
            //不显示标题栏
            navigationOptions: {
                header: null
            }
        },
        Reg: {
            screen: Reg
        },
        App: {
            screen: App
        }
    },
    {
        //默认显示页面
        initialRouteName: "App"
    }
);
export default createAppContainer(AppNavigator);

2、修改项目入口文件App.js

import React from "react";
import {createAppContainer} from "react-navigation";
//上一步创建的路由配置文件
import AppNavigator from './src/navigator/navigator'

const AppContainer = createAppContainer(AppNavigator);

export default class App extends React.Component {
    render() {
        return <AppContainer/>;
    }
}

3、页面跳转
在组件onPress方法中,使用如下方式跳转页面。
navigate方法接收2个参数
参数1:路由名称
参数2:传值,可省略

//相当于html中的 href='/Reg?key1=val1'
this.props.navigation.navigate('Reg',{key1:val1});

4、在目标页面中接收传参
getParam接收2个参数,获取不到时返回null
参数1:参数名称
参数2:默认值

this.props.navigation.getParam('paramsName',defalutValue)
<template> <div class="login-container"> <el-card class="login-card"> <h2 class="login-title">系统登录</h2> <el-form :model="loginForm" :rules="loginRules" ref="formRef" @submit.prevent="handleLogin"> <el-form-item prop="username"> <el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" /> </el-form-item> <el-form-item prop="password"> <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock" show-password /> </el-form-item> <el-button type="primary" class="login-btn" native-type="submit" :loading="loading"> 登 录 </el-button> </el-form> </el-card> </div> </template> <script setup lang="ts"> import { ref, reactive } from 'vue' import { useRouter } from 'vue-router' import { ElMessage, type FormInstance, type FormRules } from 'element-plus' import { loginApi } from '@/api/login' // 根据你的实际路径调整 const router = useRouter() const formRef = ref<FormInstance>() const loading = ref(false) // 登录表单数据 const loginForm = reactive({ username: '', password: '', }) // 表单验证规则 const loginRules = reactive<FormRules>({ username: [ { required: true, message: '请输入用户名', trigger: 'blur' }, { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }, ], password: [ { required: true, message: '请输入密码', trigger: 'blur' }, { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }, ], }) // 处理登录提交 const handleLogin = async () => { // 表单验证 const valid = await formRef.value?.validate() if (!valid) return loading.value = true try { // 调用登录API const response = await loginApi(loginForm) // ✅ 正确方式:从 response.data 中获取字段 const { code, data, msg } = response.data // 登录成功处理 ElMessage.success(msg || '登录成功') // 存储token到localStorage localStorage.setItem('token', data.token) // 跳转到首页 router.push('/index') // 其他错误处理 ElMessage.error(msg || '登录失败,请重试') } catch (error: any) { // 401错误处理 ElMessage.error('用户名或密码错误') ElMessage.error('登录请求失败:' + (error.message || '未知错误')) } finally { loading.value = false } } </script> <style scoped> .login-container { display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); } .login-card { width: 400px; padding: 30px; border-radius: 12px; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1); } .login-title { text-align: center; margin-bottom: 30px; color: #409eff; } .login-btn { width: 100%; margin-top: 10px; height: 45px; font-size: 16px; } </style> import { createRouter, createWebHistory } from 'vue-router' /* 配置路由的第一种方式:导入对应的组件 */ /* import MainLayout from '@/views/layout/MainLayout.vue' */ const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), routes: [ { path: '/', name: '', component: () => import('@/views/layout/MainLayout.vue'), /* 重定向 */ redirect: '/index', children: [ //path:代表路径 name:代表访问的时候访问的名字 component:就是访问的组件 { path: 'clazz', component: () => import('@/views/clazz/ClazzIndex.vue') }, { path: 'dept', component: () => import('@/views/dept/DepIndex.vue') }, { path: 'emp', component: () => import('@/views/emp/EmpIndex.vue') }, { path: 'stu', component: () => import('@/views/stu/StuIndex.vue') }, { path: 'index', component: () => import('@/views/index/HomeIndex.vue') }, { path: 'log', component: () => import('@/views/log/LogIndex.vue') }, { path: 'report/emp', component: () => import('@/views/report/emp/EmpIndex.vue') }, { path: 'report/stu', component: () => import('@/views/report/stu/StuIndex.vue') }, ], }, { path: '/login', component: () => import('@/views/login/LoginIndex.vue') }, ], }) export default router 登录成功后没有跳转到/index页面检查下什么问题
最新发布
07-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值