React Native - 路由

React Native - 路由 首页 / React Native入门教程 / React Native - 路由

在本章中,我们将了解React Native中的导航。

步骤1 - 安装路由

首先,我们需要安装 Router 路由,我们将在本章中使用React Native Router Flux,您可以在终端的项目文件夹中运行以下命令。

npm i react-native-router-flux --save

步骤2 - 应用代码

由于我们希望Router处理整个应用程序,因此我们将其添加到 index.ios.js 中,对于Android,您可以在 index.android.js 中执行相同的操作。

App.js

import React, { Component } from 'react';
import { AppRegistry, View } from 'react-native';
import Routes from './Routes.js'

class reactTutorialApp extends Component {
   render() {
      return (
         <Routes />
      )
   }
}
export default reactTutorialApp
AppRegistry.registerComponent('reactTutorialApp', () => reactTutorialApp)

步骤3 - 添加路由

现在,我们将在components文件夹中创建 Routes 组件,它将返回带有几个场景的 Router 。每个场景都需要键,组件和标题。Router使用key属性在场景之间切换,组件将显示在屏幕上,标题将显示在导航栏中。我们还可以将 initial 属性设置为最初要渲染的场景。

Routes.js

import React from 'react'
import { Router, Scene } from 'react-native-router-flux'
import Home from './Home.js'
import About from './About.js'

const Routes = () => (
   <Router>
      <Scene key = "root">
         <Scene key = "home" component = {Home} title = "Home" initial = {true} />
         <Scene key = "about" component = {About} title = "About" />
      </Scene>
   </Router>
)
export default Routes

步骤4 - 创建组件

我们已经有了前面各章中的 Home 组件,现在,我们需要添加关于组件,我们将添加 goToAbout 和 goToHome 函数以在场景之间切换。

链接:https://www.learnfk.comhttps://www.learnfk.com/react-native/react-native-router.html

来源:LearnFk无涯教程网

Home.js

import React from 'react'
import { TouchableOpacity, Text } from 'react-native';
import { Actions } from 'react-native-router-flux';

const Home = () => {
   const goToAbout = () => {
      Actions.about()
   }
   return (
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToAbout}>
         <Text>This is HOME!</Text>
      </TouchableOpacity>
   )
}
export default Home

About.js

import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import { Actions } from 'react-native-router-flux'

const About = () => {
   const goToHome = () => {
      Actions.home()
   }
   return (
      <TouchableOpacity style = {{ margin: 128 }} onPress = {goToHome}>
         <Text>This is ABOUT</Text>
      </TouchableOpacity>
   )
}
export default About

该应用程序将呈现初始的主页屏幕。

React Native Router

您可以按按钮切换到关于屏幕。将显示"Back"箭头;您可以使用它返回上一屏幕。

无涯教程网

React Native Router

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

许式伟的架构课 -〔许式伟〕

消息队列高手课 -〔李玥〕

苏杰的产品创新课 -〔苏杰〕

MongoDB高手课 -〔唐建法(TJ)〕

讲好故事 -〔涵柏〕

Redis源码剖析与实战 -〔蒋德钧〕

程序员的测试课 -〔郑晔〕

手把手带你写一个 MiniTomcat -〔郭屹〕

程序员职业规划手册 -〔雪梅〕

好记忆不如烂笔头。留下您的足迹吧 :)