文檔屬于翻譯官網英文 文檔。想要看原文,請https://reactnavigation.org/docs/intro/
[TOC]
### # **1. 安裝**
**NPM下安裝**
`npm install --save react-navigation`
**Yarn安裝**
`yarn add react-navigation`
以下是nmp下創建一個項目,并且安裝啟動手機調試:
~~~
# Create a new React Native App
react-native init SimpleApp
cd SimpleApp
# Install the latest version of react-navigation from npm
npm install --save react-navigation
# Run the new app
react-native run-android # or:
react-native run-ios
~~~
當安裝啟動成功后。
頁面會顯示:`welcome react-native`
> 在當前目錄下,創建app.js。并且用import './App';. 來導入它。同時將index.ios.js和 index.android.js里面的內容清除掉。顯示內容放在app.js
> 這樣就可以顯示一個只有導入,導出的一個清爽首頁了。
* * * * *
### # **2. 引入堆棧導航器**
迫不及待的想要體驗堆棧導航器了吧,何不現在我們就開始!
1.在跟index.android.js同目錄下創建app.js
2.在index.android.js中代碼如下:
~~~
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import { ChatScreen,HelloScreen } from './app';
class HomeScreen extends Component {
static navigationOptions = {
title: 'Home',
};
render() {
const { navigate } = this.props.navigation;
return (
<View>
<Text>Hello, Chat App!代碼控制臺</Text>
<Button
onPress={() => navigate('Chat')}
title="Go Chat"
/>
</View>
);
}
}
const SimpleApp = StackNavigator({
Home: { screen: HomeScreen },
Chat: { screen: ChatScreen },
});
AppRegistry.registerComponent('tang', () => SimpleApp);
~~~
### # **3.app.js頁面代碼如下:**
~~~
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button
} from 'react-native';
export class ChatScreen extends Component {
static navigationOptions = {
title: 'Chat',
};
render() {
return (
<View>
<Text>Chat with Lucy</Text>
</View>
);
}
}
~~~
插入數據線,打開cmd命令進入應用所在根目錄。
運行命令:
`react-native run-android`
等在手機安裝完畢后,就可以看見運行結果了。
### #**4 .傳遞參數**
場景:頭部導航組件樣式都一樣,文字內容不一樣,應該怎么實現。
要實現導航器之間的傳遞參數就應該在上一級頁面導航器中定義 一個參數,然后在子頁面或者下級頁面接收完成傳遞。
1.我們更改index.android.js中的Button
~~~
<Button
onPress={() => navigate('Chat', { user: 'Lucy' })}
title="Chat with Lucy"
/>
~~~
通過navigate中傳遞一個數組來實現傳值。
2.app.js中獲取傳值。
~~~
render() {
// The screen's current route is passed in to `props.navigation.state`:
const { params } = this.props.navigation.state;
return (
<View>
<Text>Chat with {params.user}</Text>
</View>
);
}
~~~
### #**5 .擴展閱讀:**
props(屬性)
http://reactnative.cn/docs/0.47/props.html#content
state(狀態)
http://reactnative.cn/docs/0.47/state.html#content