- React Native 教程
- React Native - 首页
- 核心概念
- React Native - 概述
- React Native - 环境设置
- React Native - 应用
- React Native - 状态
- React Native - 属性
- React Native - 样式
- React Native - Flexbox
- React Native - ListView
- React Native - 文本输入
- React Native - ScrollView
- React Native - 图片
- React Native - HTTP
- React Native - 按钮
- React Native - 动画
- React Native - 调试
- React Native - 路由
- React Native - 运行 iOS
- React Native - 运行 Android
- 组件和 API
- React Native - View
- React Native - WebView
- React Native - Modal
- React Native - ActivityIndicator
- React Native - Picker
- React Native - 状态栏
- React Native - Switch
- React Native - Text
- React Native - Alert
- React Native - Geolocation
- React Native - AsyncStorage
- React Native 有用资源
- React Native - 快速指南
- React Native - 有用资源
- React Native - 讨论
React Native - 路由
在本章中,我们将了解 React Native 中的导航。
步骤 1:安装路由器
首先,我们需要安装路由器。在本章中,我们将使用 React Native Router Flux。您可以从项目文件夹中的终端运行以下命令。
npm i react-native-router-flux --save
步骤 2:整个应用程序
由于我们希望我们的路由器处理整个应用程序,因此我们将在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。每个场景都需要key、component和title。Router 使用 key 属性在场景之间切换,component 将在屏幕上呈现,标题将显示在导航栏中。我们还可以将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组件;现在,我们需要添加About组件。我们将添加goToAbout和goToHome函数以在场景之间切换。
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
应用程序将呈现初始Home屏幕。
您可以按下按钮切换到关于屏幕。后退箭头将出现;您可以使用它返回到上一个屏幕。
广告