react-navigation分为三个部分StackNavigator、TabNavigator、DrawerNavigator,本文主要介绍StackNavigator的用法。
使用前先安装npm install --save react-navigation
,这是官方API https://reactnavigation.org/docs/stack-navigator.html
下面是例子,有详细注释:
App.js
import React, { Component } from 'react';
import styles from './style/styles';
import {HomeScreen} from './views/HomeScreen';
import {SecondScreen} from './views/SecondScreen';
import {StackNavigator} from 'react-navigation';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
const App = StackNavigator(
{
Home:{
screen:HomeScreen
},
SecondScreen:{
screen:SecondScreen,
navigationOptions:{
headerTitle:'第二页'
}//设置SecondScreen界面的title、导航条样式
}
},//指定界面 ,本例有两个界面HomeScreen,SecondScreen
{
initialRouteName:'Home',//设置默认页面,不写默认第一个
navigationOptions:{
headerStyle:{//设置导航条的样式。背景色,宽高等
backgroundColor:'#d5522e'
},
headerTintColor:'#0ff',
headerTitleStyle:{//设置导航条文字样式
fontWeight:'bold'
}
}
}//统一设置各个界面title、导航条样式
);
export default App;
HomeScreen.js
import React, { Component } from 'react';
import styles from '../style/styles';
import {
View,
Text,
Button,
} from 'react-native';
//默认页面
export class HomeScreen extends Component {
static navigationOptions = {//设置SecondScreen界面的title、导航条样式
title: '首页',
headerRight:(
<Button
title= '详情'
color='#d96'
onPress={()=> alert('hint','button !!!')}
/>
)
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Button
title="Juump profile"
onPress={() => {
navigate('SecondScreen', { itemId: 86, otherParam: 'anything you want here' });//跳转页面 并传递参数,第一个参数决定跳转的页面,第二个参数是传递的参数
}}
/>
</View>
);
}
}
SecondScreen.js
/* @flow */
import React, { Component } from 'react';
import styles from '../style/styles';
import {
View,
Text,
Button,
} from 'react-native';
export class SecondScreen extends Component {
render() {
const { navigate } = this.props.navigation;
const {params} = this.props.navigation.state;//接收参数
const itemId = params ? params.itemId: null;
const otherParam = params ? params.otherParam: null;
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'flex-start'}}>
<Text style={{ height:40}}>itemId: {JSON.stringify(itemId)}</Text>{/*将上个页面传递的参数设置到Text上 */}
<Text style={{ height:40}}>otherParam: {JSON.stringify(otherParam)}</Text>
<Button
style={{ flex: 3}}
title="Go back"
onPress={() => this.props.navigation.goBack()}//返回上一页
/>
</View>
);
}
}
界面目录