React导航如何将相同参数从屏幕传递到初始路线

omvjsjqw  于 2022-11-30  发布在  React
关注(0)|答案(1)|浏览(107)

关于ReactNavigation文档,他们说通过使用getStateFromPath()的自定义实现,可以将相同的参数从屏幕传递到初始路径
https://reactnavigation.org/docs/configuring-links#rendering-an-initial-route

有没有人能给我展示一个例子,说明如何实现一个自定义的getStateFromPath,以将相同的参数从一个屏幕传递到下面的例子中的初始路由?
示例:

const config: {
  initialRouteName?: any;
  screens: PathConfigMap<RootStackParamsList>;
} = {
    initialRouteName: "ScreenA",
    screens: {
        ScreenA: {
            path: "ScreenA",
            parse: {
                param1: Number,
                param2: Number
            }
        },
        screenB: {
            path: "ScreenB/param1/param2",
            parse: {
                param1: Number,
                param2: Number
            }
        }
    }
}

const linkingOptions: LinkingOptions<ReactNavigation.RootParamList> = {
  prefixes: [Linking.makeUrl("/")],
  config: config,
  getStateFromPath(path, config) {
    // Get params from ScreenB and copy them for screenA
  }
}
q0qdq0h2

q0qdq0h21#

您正在返回getStateFromPath()中的路由状态。

import { getStateFromPath } from "@react-navigation/native";

getStateFromPath(path, options) {
    if (path.includes("ScreenB")) {
      const params = getStateFromPath(path, options)?.routes[0].params;
      return {
        routes: [
          {
            name: "ScreenA",
            params: {
              ...params,
            },
          },
        ],
      };
    }
    return getStateFromPath(path, options);
  }

相关问题