React Navigation 基本使用

参考资料

https://reactnavigation.org/docs/

环境搭建

Minimum requirementsreact-native >= 0.63.0

  • expo >= 41 (if you use Expo)
  • typescript >= 4.1.0 (if you use TypeScript)

Installation

npm install @react-navigation/native
npm install react-native-screens react-native-safe-area-context

From React Native 0.60 and higher, linking is automatic. So you don’t need to run react-native link.

If you’re on a Mac and developing for iOS, you need to install the pods (via Cocoapods) to complete the linking.

npx pod-install ios

react-native-screens package requires one additional configuration step to properly work on Android devices. Edit MainActivity.java file which is located in android/app/src/main/java/<your package name>/MainActivity.java.

@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(null);
}

and make sure to add an import statement at the top of this file:

import android.os.Bundle;

Hello React Navigation

React Navigation提供了不同于浏览器的a标签的方案,它提供了适用了IOS和Android合适的过渡动画。

安装原生栈导航库(Installing the native stack navigator library)

到目前为止我们已经安装的库仅仅构建了Navigation的基本快,然而每个Navigation都是有一个自己的库的,为了使用原声的导航栈,我们需要安装@react-navigation/native-stac

npm install @react-navigation/native-stack

@react-navigation/native-stack depends on react-native-screens and the other libraries that we installed in Getting started. If you haven’t installed those yet, head over to that page and follow the installation instructions.

创建一个原生栈导航(Creating a native stack navigator)

createNativeStackNavigator函数会返回一个包含两个属性ScreenNavigator的对象。他们都是用于配置配置navigator的React组件,Navigator应该包含Screen元素作为他们的子元素来为路由定义配置。

NavigationContainer是一个用来管理导航树(navigation tree)的组件并且它包含了 navigation state,这个组件必须包含所有导航的结构,通常的,我们在app的根去渲染这个组件,通常这个组件被App.js被导出。(export)

// In App.js in a new project
import * as React from 'react';
import { View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';function HomeScreen() {return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>Home Screen</Text></View>);
}const Stack = createNativeStackNavigator();function App() {return (<NavigationContainer><Stack.Navigator><Stack.Screen name="Home" component={HomeScreen} /></Stack.Navigator></NavigationContainer>);
}export default App;

基本案例

// In App.js in a new project
import * as React from 'react';
import { View, Text, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';function HomeScreen({navigation}) {return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>Home Screen</Text><Buttontitle="Go to Details"onPress={() => {navigation.navigate('Details', {itemId: 86,otherParam: 'anything you want here'})}}/></View>);
}function DetailsScreen({route,navigation}) {const { itemId, otherParam } = route.params;return (<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}><Text>Details Screen</Text><Text>itemId: {JSON.stringify(itemId)}</Text><Text>otherParam: {JSON.stringify(otherParam)}</Text><Buttontitle="Go to Details... again"onPress={() =>navigation.push('Details', {itemId: Math.floor(Math.random() * 100),})}/><Button title="Go back" onPress={() => navigation.goBack()} /><Buttontitle="Go back to first screen in stack"onPress={() => navigation.popToTop()}/></View>);
}const Stack = createNativeStackNavigator();function App() {return (<NavigationContainer><Stack.Navigator initialRouteName="Home"><Stack.Screen name="Home" component={HomeScreen} options={{ title: '主页' }}/><Stack.Screen name="Details" component={DetailsScreen} options={{ title: '详情' }}/></Stack.Navigator></NavigationContainer>);
}export default App;

携返回值案例

// In App.js in a new project
import * as React from "react";
import { View, Text, Button, TextInput } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";function HomeScreen({ navigation, route }) {React.useEffect(() => {if (route.params?.post) {// Post updated, do something with `route.params.post`// For example, send the post to the server}}, [route.params?.post]);return (<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}><Buttontitle="Create post"onPress={() => navigation.navigate("CreatePost")}/><Text style={{ margin: 10 }}>Post: {route.params?.post}</Text></View>);
}function CreatePostScreen({ navigation, route }) {const [postText, setPostText] = React.useState("");return (<><TextInputmultilineplaceholder="What's on your mind?"style={{ height: 200, padding: 10, backgroundColor: "white" }}value={postText}onChangeText={setPostText}/><Buttontitle="Done"onPress={() => {// Pass and merge params back to home screennavigation.navigate({name: "Home",params: { post: postText },merge: true,});}}/></>);
}const Stack = createNativeStackNavigator();function StackScreen() {const screenOptions = {headerStyle: {backgroundColor: "#f4511e",},headerTintColor: "#fff",headerTitleStyle: {fontWeight: "bold",},}return (<Stack.Navigator initialRouteName="Home"><Stack.Screenname="Home"component={HomeScreen}options={{title: "主页", ...screenOptions }}/><Stack.Screenname="CreatePost"component={CreatePostScreen}options={{title: "创建Post", ...screenOptions }}/></Stack.Navigator>);
}function App() {return (<NavigationContainer><StackScreen /></NavigationContainer>);
}export default App;

Replacing the title with a custom component

function LogoTitle() {return (<Imagestyle={{ width: 50, height: 50 }}source={require('@expo/snack-static/react-native-logo.png')}/>);
}function StackScreen() {return (<Stack.Navigator><Stack.Screenname="Home"component={HomeScreen}options={{ headerTitle: (props) => <LogoTitle {...props} /> }}/></Stack.Navigator>);
}

给标题来点样式

// In App.js in a new project
import * as React from "react";
import { View, Text, Button, TextInput } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";function HomeScreen({ navigation, route }) {React.useEffect(() => {if (route.params?.post) {// Post updated, do something with `route.params.post`// For example, send the post to the server}}, [route.params?.post]);return (<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}><Buttontitle="Create post"onPress={() => navigation.navigate("CreatePost")}/><Text style={{ margin: 10 }}>Post: {route.params?.post}</Text></View>);
}function CreatePostScreen({ navigation, route }) {const [postText, setPostText] = React.useState("");return (<><TextInputmultilineplaceholder="What's on your mind?"style={{ height: 200, padding: 10, backgroundColor: "white" }}value={postText}onChangeText={setPostText}/><Buttontitle="Done"onPress={() => {// Pass and merge params back to home screennavigation.navigate({name: "Home",params: { post: postText },merge: true,});}}/></>);
}const Stack = createNativeStackNavigator();function StackScreen() {const screenOptions = {headerStyle: {backgroundColor: "#f4511e",},headerTintColor: "#fff",headerTitleStyle: {fontWeight: "bold",},}return (<Stack.Navigator initialRouteName="Home"><Stack.Screenname="Home"component={HomeScreen}options={{headerTitle: () => <Text>Text</Text>,headerRight: () => (<ButtononPress={() => alert('This is a button!')}title="Info"color="black"/>),}}/><Stack.Screenname="CreatePost"component={CreatePostScreen}options={{headerTitle: () => <Text>Text</Text>,headerRight: () => (<ButtononPress={() => alert('This is a button!')}title="Info"color="black"/>),}}/></Stack.Navigator>);
}function App() {return (<NavigationContainer><StackScreen /></NavigationContainer>);
}export default App;

Tab.Navigator

import * as React from 'react';
import { Text, View, Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';import Ionicons from 'react-native-vector-icons/Ionicons';
function HomeScreen({ navigation }) {return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Text>Home!</Text><Buttontitle="Go to Settings"onPress={() => navigation.navigate('Settings')}/></View>);
}function SettingsScreen({ navigation }) {return (<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Text>Settings!</Text><Button title="Go to Home" onPress={() => navigation.navigate('Home')} /></View>);
}export default function App() {const Tab = createBottomTabNavigator();return (<NavigationContainer><Tab.NavigatorscreenOptions={({ route }) => ({tabBarIcon: ({ focused, color, size }) => {let iconName;if (route.name === 'Home') {iconName = focused? 'ios-information-circle': 'ios-information-circle-outline';} else if (route.name === 'Settings') {iconName = focused ? 'ios-list' : 'ios-list';}// You can return any component that you like here!return <Ionicons name={iconName} size={size} color={color} />;},tabBarActiveTintColor: 'tomato',tabBarInactiveTintColor: 'gray',})}><Tab.Screen name="Home" component={HomeScreen} options={{ tabBarBadge: 3 }}/><Tab.Screen name="Settings" component={SettingsScreen} /></Tab.Navigator></NavigationContainer>);
}

隐藏顶部导航栏的一些办法

可以设置headerShown: false

<NavigationContainer><Stack.Navigator initialRouteName="Index"><Stack.Screenname="Index"component={IndexScreen}options={{ title: "主页" }, {headerShown: false}}  /></Stack.Navigator>
</NavigationContainer>
<Tab.Navigator><Tab.Screen name="Home" component={HomeScreen} options={{headerShown:false}}/><Tab.Screen name="Settings" component={SettingsScreen} />
</Tab.Navigator>

Stack Navigation常用配置

<Stack.Screen
// 具体参数设定请参考:https://reactnavigation.org/docs/native-stack-navigator#optionsname="Details"component={DetailsScreen}options={{title: "详情"},{animation: "slide_from_right"},// 划入方式// {headerTitleAlign:"center"}, // 标题居中(近Android,IOS默认居中)// {presentation: "formSheet"}, // 几乎仅IOS支持{headerShown: true } // 不要隐藏标题,放到最后面写
}
/>

综合案例

import * as React from "react";
import { Text, View, Button, Dimensions } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import Ionicons from "react-native-vector-icons/Ionicons";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { SafeAreaView } from "react-native-safe-area-context";// 主页
function IndexScreen({ navigation }) {function HomeScreen() {return (<SafeAreaView edges={['top', 'left', 'right']}style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}><Buttontitle="Go to Details"onPress={() => navigation.navigate("Details")}/></SafeAreaView>);}function SettingsScreen() {return (<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}><Text>Settings!</Text></View>);}const Tab = createBottomTabNavigator();Tab.navigationOptions = ({navigation}) => {//  关键这一行设置 header:nullreturn{header: null,}};return (<Tab.Navigator><Tab.Screen name="Home" component={HomeScreen}options={{headerShown:false}}/><Tab.Screen name="Settings" component={SettingsScreen} /></Tab.Navigator>);
}function DetailsScreen({ navigation }) {return (<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}><Text>Home Screen</Text><Button title="Go back" onPress={() => navigation.goBack()} /></View>);
}export default function App() {const Stack = createNativeStackNavigator();return (<NavigationContainer><Stack.Navigator initialRouteName="Index"><Stack.Screenname="Index"component={IndexScreen}options={// headerTitleAlign和 headerShown最好别混用{title: "主页"}, {animation: "slide_from_right"},{headerShown: false}}  /><Stack.Screen// 具体参数设定请参考:https://reactnavigation.org/docs/native-stack-navigator#optionsname="Details"component={DetailsScreen}options={{title: "详情"},// {headerTitleAlign:"center"}, // 标题居中(近Android,IOS默认居中)// {presentation: "formSheet"}, // 几乎仅IOS支持{animation: "slide_from_right"},// 划入方式{headerShown: true } // 不要隐藏标题}  /></Stack.Navigator></NavigationContainer>);
}

React Navigation 基本使用相关推荐

  1. 使用Redux在React Navigation App中管理状态

    by Andrea Bizzotto 通过安德里亚·比佐托(Andrea Bizzotto) 使用Redux在React Navigation App中管理状态 (Managing State in ...

  2. react navigation 中使用goBack()跳转到指定页面

    一.适用场景: 在app端开发的时候,相反回到某一个页面的时候保持跳转页面的所有状态不更新,也就是说不触发新的生命周期. 例如:A-->B-->C-->D 要想从D页面直接返回到B页 ...

  3. RN路由-React Navigation组件5.x-基本原理(中文文档)

    ##引言 React Native路由导航,有它就够了!该文档根据React Navigation文档翻译,有些内容会根据自己的理解进行说明,不会照搬直译,若发现理解有问题的地方,欢迎大家提点!由于本 ...

  4. React Navigation 路由导航库升级 5.x

    当前版本:3.0.0 升级版本:5.12.8 安装依赖 $ yarn add   @react-navigation/native   @react-navigation/stack   @react ...

  5. react navigation中使用goBack返回指定页面

    goBack 首先, 现在看一下react navigation官网中对goBack的描述: goBack的参数为页面的key, 这个key是系统随机分配的, 而不是手动设置的routeName, 所 ...

  6. Facebook力推导航库:React Navigation使用详解

    本文来自Songlcy投稿:文章地址:http://blog.csdn.net/u013718120/article/details/72357698 一.开源库介绍 今年1月份,新开源的react- ...

  7. React Native之React Navigation踩坑

    自动重装系统之后,已经很长一段时间没有来写React Native了,今天空闲之余,决定重新配置React Native的开发环境,继续踩坑... React Native的开发环境配置狠简单,只要依 ...

  8. React Navigation 导航栏样式调整+底部角标消息提示

    五一佳节匆匆而过,有人选择在外面看人山人海,有人选择宅在家中度过五一,也有人依然坚守在第一线,致敬! 这是坚持学习react-native的第二篇文章,可能会迟到,但是绝不会缺席,这篇要涉及到的是re ...

  9. 解决React Navigation goBack()无效

    import { StackActions } from "react-navigation"; const popAction = StackActions.pop({n: 1} ...

最新文章

  1. Saiku二次开发获取源代码在本地编译(五)
  2. WaitForSingleObject和WaitForMultipleObjects用法
  3. selective gaussian blur /adaptive-blur
  4. Android缩放比例公式,android开发 缩放到指定比例的尺寸
  5. JBoss AS 7.1.0.Final“ Thunder”发布-Java EE 6 Full Profile认证!
  6. 《当程序员的那些狗日日子》(三十六)无名的配角
  7. AndroidMainfest.xml具体解释——lt;activitygt;
  8. 在vscode中怎样debug调试go程序
  9. 春天的旁边_春天@PropertySource
  10. VS2008添加ODBC数据源崩溃
  11. DELPHI学习---简单类型
  12. mysql 查询优化 ~ 善用profie利器
  13. Java 虚拟机启动
  14. 毕业论文格式修改方法
  15. 计算机软考高级论文怎么写,【干货】软考高级论文怎么写易得高分?
  16. 【Verilog语法简介】
  17. Overload和Override详解
  18. java开发手机app教程,看完必懂
  19. 模模搭古城搭建学习笔记2:基础设施篇
  20. 【PCL】点云库PCL常见错误

热门文章

  1. 洛谷 P1039 侦探推理
  2. python爬取京东手机参数_python爬取京东手机价格
  3. 基于SSM的智慧问诊系统
  4. iOS开发icon图标设置
  5. 2023年重庆大学中国语言文学考研考情与难度、参考书及前辈经验
  6. 油猴脚本Tampermonkey的简介和安装使用,五分钟安装
  7. 剑桥学霸强烈推荐:每天花20分钟看这些视频,英语水平暴增
  8. 推广你的网站,从学会写软文开始
  9. 搜索引擎排名优化技巧有哪些
  10. 实时群控,苹果群控,手机群控,IOS群控,批量手机操作,批量手机控制,同步操作