react-navigation 6.x版本的安装、传参、navigator的使用等介绍(part3)。
目前react-navigation的官方文档已经更新到了6.x版本,在官方文档中对于其基本的使用方法也有所介绍,但是对于一些比较复杂的使用场景,或者传参等细节问题并没有给出详细的解决方案。
在这篇文章中,我将介绍不同页面之间参数的传递和 Link的使用。
页面导航与参数传递
navigation.navigate & navigation.replace
在官方文档中给出了navigation.navigate参数传递的基本方式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
   | import * as React from 'react'; import { Text, View, Button } from 'react-native'; import { NavigationContainer } from '@react-navigation/native'; import { createNativeStackNavigator } from '@react-navigation/native-stack';
  function HomeScreen({ navigation }) {     return (         ......         <Button             title="Go to Details"             onPress={() => {                          navigation.navigate('Details', {                 itemId: 86,                 otherParam: 'anything you want here',             });             }}         />         ......     ); }
  function DetailsScreen({ route, navigation }) {          const { itemId } = route.params;     const { otherParam } = route.params;     return (     ......     ); }
  const Stack = createNativeStackNavigator();
  export default function App() {   return (     <NavigationContainer>       <Stack.Navigator>         <Stack.Screen name="Home" component={HomeScreen} />         <Stack.Screen name="Details" component={DetailsScreen} />       </Stack.Navigator>     </NavigationContainer>   ); }
   | 
 
如果需要传递参数,需要在函数上加入navigation的参数,如果需要接受接受参数, 则需要加入route并使用route.params获得参数。
navigation.replace和navigation.navigate传递参数的方式是一样的,区别是navigation.navigate相当于新压入一个页面,回退的时候还是会回退到当前页面,navigation.replace是以新页面替换掉了当前页面。
Link的使用以及参数传递
使用Link也可以帮助我们在不同页面之间进行导航,与navigation.navigate相比,Link更加自由,因为它不需要在函数上加上navigation的参数。
基本用法
在官方文档提供了基本的用法。
参数传递和接收
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
   | import {Link} from '@react-navigation/native'; ...
 
  const Card = ({props, userId}) => {     ...     return (         ...             <Link{% raw %}             to={{                 screen: 'Detail',                 initial: false,                 params: {props: props, userId: userId},             }}>{% endraw %}                 <Text mt={0.02 * w} color="#71717a" bold size="xl">                     {title}                 </Text>             </Link>         ...         </Box>     ); };
 
  const DetailScreen = ({route}) => {          const {props} = route.params;     const {userId} = route.params;     const {groupId} = props.groupId;
      return (         <>         ...         </>     ); };
  | 
 
在使用Link的时候,screen是我们希望导航到的页面名字(这个名字必须已经在Navigator中定义过了),params中使用key:value方式传递参数,在目标页面使用route.params接受参数(注意在函数参数中一定要加入route)。
结语
通过这三篇文章,我基本上将我所接触到的react-navigation的基本用法和使用中遇到问题的解决方案做了介绍。react-navigation的更新还是非常快速的,并且相对于历史版本,语法上有了比较大的变动,最后还是要以官方文档作为最重要的参考。