使用第三方导航库React Navigation
第一步:安装
yarn add @react-navigation/native
安装react-navigation的依赖库
yarn add react-native-screens react-native-safe-area-context
使用stack导航(类似OS中的NavigationController)
yarn add @react-navigation/native-stack
使用bottom tab导航(类似OS中的TabController)
yarn add @react-navigation/bottom-tabs
如果是iOS上跑程序,就需要重新去pod install
,把上面新增的库,下载到工程本地
第二步:配置
- 新建2个页面MyHomeScreen,DetailScreen,用于展示界面的跳转
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
// create a component
const HomeScreen = ({ navigation }) => {
goToDetailScreen = () => {
navigation.navigate('Details')
}
return (
<View style={styles.container}>
<Text>HomeScreen</Text>
<Button title='to detail screen' onPress={goToDetailScreen}></Button>
</View>
);
};
// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5f5f5',
},
});
//make this component available to the app
export default HomeScreen;
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
// create a component
const DetailScreen = ({ navigation }) => {
goBackToHomeScreen = () => {
// navigation.goBack()
navigation.popToTop()
}
return (
<View style={styles.container}>
<Text>DetailScreen</Text>
<Button title='back to home screen' onPress={goBackToHomeScreen}></Button>
</View>
);
};
// define your styles
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#f5f5f5',
},
});
//make this component available to the app
export default DetailScreen;
-
在app.js界面进行导航的配置工作
image.png
先是导入库,导入Screen,然后,就是配置一下导航
<NavigationContainer>
<Stack.Navigator initialRouteName="Home">
<Stack.Screen name="Home" component={MyHomeScreen} />
<Stack.Screen name="Details" component={MyDetailScreen} />
</Stack.Navigator>
</NavigationContainer>
使用
从Home界面进入到Detail界面
goToDetailScreen = () => {
navigation.navigate('Details')
}
从Detail界面返回到Home界面
goBackToHomeScreen = () => {
// navigation.goBack()
navigation.popToTop()
}
最终效果:
navigation.gif
结尾
后续会在本文的基础上,做一些更多场景导航的实例,今天RN 的分享就到这里喽,小伴们,觉得有点用的话,或者已经看到这里面来的请点个赞加关注吧~~ 后续分享更多有关RN Flutter和移动端原生开发相关的文章。欢迎在下面留言交流。
网友评论