React Native - 路由器
-
简述
在本章中,我们将了解 React Native 中的导航。 -
第 1 步:安装路由器
首先,我们需要安装Router. 我们将在本章中使用 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)
-
第三步:添加路由器
现在我们将创建Routes组件文件夹中的组件。它会回来Router有几个场景。每个场景都需要key, component和title. Router 使用 key 属性在场景之间切换,组件将呈现在屏幕上,标题将显示在导航栏中。我们还可以设置initial属性到最初要渲染的场景。路由.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屏幕。您可以按 按钮切换到about屏幕。将出现后退箭头;您可以使用它返回上一个屏幕。