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、componenttitle。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元件。我們將新增goToAboutgoToHome函式以在場景之間切換。

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螢幕。

React Native Router

您可以按下按鈕切換到關於螢幕。後退箭頭將出現;您可以使用它返回到上一個螢幕。

React Native Router
廣告