react-navigation的使用
2018-12-26 本文已影响0人
暖羊羊_d603
创建了一个新的工程,并且可以运行起来,也能展示基本出helloword了,就想着 用一下导航, 本以为很简单 ,结果一运行就报错 ,记录一下过程
在当前目录操作:
- 需要添加库:
yarn add react-navigation
- 添加完1后 运行会报错 undefined is not an object (evaluating ‘RNGeatureHandlerModule.State’) 因为还需要添加下面的库
yarn add react-native-gesture-handler
- (链接原生库)
react-native link
最后就是编写代码了
App.js
import React,{ Component } from 'react';
import {createStackNavigator,createAppContainer} from 'react-navigation';
import HomeScreen from "./HomeScreen";
import DetailsScreen from "./DetailsScreen";
const RootStack = createStackNavigator({
Home: {
screen: HomeScreen
},
Details: {
screen: DetailsScreen
}
})
const App = createAppContainer(RootStack);
export default App;
HomeScreen.js
import React, { Component } from 'react';
import {View,StyleSheet,Text,Button} from 'react-native';
import {createStackNavigator,createAppContainer} from 'react-navigation';
export default class HomeScreen extends Component{
static navigationOptions = {
title:'Home', //设置导航条标题
};
render(){
const navigate = this.props.navigation;
return (
<View style={{flex:1, alignItems: 'center',justifyContent: 'center'}}>
<Text>HomeScreen</Text>
<Button
title="Go to Details"
onPress={() => navigate.navigate('Details')}
/>
</View>
);
}
}
DetailsScreen.js
import React, { Component } from 'react';
import {View,Text,Button} from 'react-native';
import {createStackNavigator,createAppContainer} from 'react-navigation';
export default class DetailsScreen extends Component{
static navigationOptions = {
title:'Details', //设置导航条标题
};
render(){
const navigate = this.props.navigation;
return (
<View style={{flex:1, alignItems: 'center',justifyContent: 'center'}}>
<Text>Details Screen</Text>
<Button
title="Go to Details"
onPress={() => navigate.push('Details')}
/>
<Button
title="Go to Home"
onPress={() => navigate.navigate('Home')}
// 跳转到导航中定义的路由 ,当前的路由 如果已经存在 则会跳转到,不存在 则什么都不发生 否则 本例子中相当于pop
/>
<Button
title="Go Back"
onPress={() => navigate.goBack()}
/>
</View>
);
}
}