获取 React Navigation,就必须安装 react-navigation npm 包。
NPM方式安装
npm install --save react-navigation
或 Yarn方式安装
yarn add react-navigation
创建一个StackNavigator
RootNavigator.js:
import React from 'react';
import { View, Text } from 'react-native';
import { StackNavigator } from 'react-navigation';
const HomeScreen = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
</View>
);
const DetailsScreen = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
const RootNavigator = StackNavigator({
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
});
export default RootNavigator;
为上面的n添加按钮事件,即可点击切换内容:
import React from 'react';
import { View, Text, Button } from 'react-native';
import { StackNavigator } from 'react-navigation';
const HomeScreen = ({ navigation }) => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Home Screen</Text>
<Button
onPress = {() => navigation.navigate('Details')}
title = "Go to details"
/>
</View>
);
const DetailsScreen = () => (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text>Details Screen</Text>
</View>
);
const RootNavigator = StackNavigator({
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
});
export default RootNavigator;
在App.js 使用:
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
import RootNavigator from './RootNavigator';
export default class App extends Component<{}> {
render() {
return (
<View style={styles.container}>
<RootNavigator/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#f5fcff',
marginTop: 80,
}
});