React Native目前有幾個內置的導航器組件,一般來說我們首推Navigator
。它使用純JavaScript實現了一個導航棧,因此可以跨平台工作
場景簡單來說其實就是一個全屏的React組件。與之相對的是單個的Text
、Image
又或者是你自定義的什么組件,僅僅占據頁面中的一部分。
下面我們來定義一個僅顯示一些文本的簡單場景。創建一個名為“MyScene.js”的文件,然后粘貼如下代碼:
import React, { Component } from 'react'; import { View, Text } from 'react-native'; export default class MyScene extends Component { static defaultProps = { title: 'MyScene' }; render() { return ( <View> <Text>Hi! My name is {this.props.title}.</Text> </View> ) } }
注意組件聲明前面的export default
關鍵字。它的意思是導出(export)當前組件,以允許其他組件引入(import)和使用當前組件
// ./MyScene表示的是當前目錄下的MyScene.js文件,也就是我們剛剛創建的文件 // 注意即便當前文件和MyScene.js在同一個目錄中,"./"兩個符號也是不能省略的! // 但是.js后綴是可以省略的 import MyScene from './MyScene'; class YoDawgApp extends Component { render() { return ( <MyScene /> ) } } AppRegistry.registerComponent('YoDawgApp', () => YoDawgApp);
場景已經說的夠多了,下面我們開始嘗試導航跳轉。首先要做的是渲染一個Navigator
組件,然后通過此組件的renderScene
屬性方法來渲染其他場景。
render() {
return ( <Navigator initialRoute={{ title: 'My Initial Scene', index: 0 }} renderScene={(route, navigator) => { return <MyScene title={route.title} /> }} /> ); }
使用導航器經常會碰到“路由(route)”的概念。“路由”抽象自現實生活中的路牌,在RN中專指包含了場景信息的對象。renderScene
方法是完全根據路由提供的信息來渲染場景的。你可以在路由中任意自定義參數以區分標記不同的場景,我們在這里僅僅使用title
作為演示。
要過渡到新的場景,你需要了解push
和pop
方法。這兩個方法由navigator
對象提供,而這個對象就是上面的renderScene
方法中傳遞的第二個參數。 我們使用這兩個方法來把路由對象推入或彈出導航棧
import React, { Component } from 'react'; import { AppRegistry, Navigator, Text, View } from 'react-native'; import MyScene from './MyScene'; class SimpleNavigationApp extends Component { render() { return ( <Navigator initialRoute={{ title: 'My Initial Scene', index: 0 }} renderScene={(route, navigator) => <MyScene title={route.title} // Function to call when a new scene should be displayed onForward={ () => { const nextIndex = route.index + 1; navigator.push({ title: 'Scene ' + nextIndex, index: nextIndex, }); }} // Function to call to go back to the previous scene onBack={() => { if (route.index > 0) { navigator.pop(); } }} /> } /> ) } } AppRegistry.registerComponent('SimpleNavigationApp', () => SimpleNavigationApp);
對應的MyScene.js代碼如下:
import React, { Component, PropTypes } from 'react'; import { View, Text, TouchableHighlight } from 'react-native'; export default class MyScene extends Component { static propTypes = { title: PropTypes.string.isRequired, onForward: PropTypes.func.isRequired, onBack: PropTypes.func.isRequired, } render() { return ( <View> <Text>Current Scene: { this.props.title }</Text> <TouchableHighlight onPress={this.props.onForward}> <Text>點我進入下一場景</Text> </TouchableHighlight> <TouchableHighlight onPress={this.props.onBack}> <Text>點我返回上一場景</Text> </TouchableHighlight> </View> ) } }