react-navigation 6.x 使用指南 (3)

目前react-navigation的官方文档已经更新到了6.x版本,在官方文档中对于其基本的使用方法也有所介绍,但是对于一些比较复杂的使用场景,或者传参等细节问题并没有给出详细的解决方案。

在这篇文章中,我将介绍不同页面之间参数的传递和 Link的使用。

页面导航与参数传递

官方文档中给出了navigation.navigate参数传递的基本方式:

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={() => {
            /* 1. Navigate to the Details route with params */
            navigation.navigate('Details', {
                itemId: 86,
                otherParam: 'anything you want here',
            });
            }}
        />
        ......
    );
}

function DetailsScreen({ route, navigation }) {
    /* 2. Get the param */
    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.replacenavigation.navigate传递参数的方式是一样的,区别是navigation.navigate相当于新压入一个页面,回退的时候还是会回退到当前页面,navigation.replace是以新页面替换掉了当前页面。

Link的使用以及参数传递

使用Link也可以帮助我们在不同页面之间进行导航,与navigation.navigate相比,Link更加自由,因为它不需要在函数上加上navigation的参数。

基本用法

官方文档提供了基本的用法。

参数传递和接收

import {Link} from '@react-navigation/native';
...

// 参数的传出
const Card = ({props, userId}) => {
    ...
    return (
        ...
            <Link
            to={{
                screen: 'Detail',
                initial: false,
                params: {props: props, userId: userId},
            }}>
                <Text mt={0.02 * w} color="#71717a" bold size="xl">
                    {title}
                </Text>
            </Link>
        ...
        </Box>
    );
};

// 参数的接受
const DetailScreen = ({route}) => {
    // console.log('detail screen', route.params);
    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的更新还是非常快速的,并且相对于历史版本,语法上有了比较大的变动,最后还是要以官方文档作为最重要的参考。




Enjoy Reading This Article?

Here are some more articles you might like to read next:

  • 大三总结
  • Github pages + jekyll 博客搭建
  • git常用命令
  • docker命令记录
  • macbook m1 + VMware Fusion 配置ubuntu虚拟机