如何在TypeScript中使用navigation.replace?

问题描述 投票:0回答:4

我正在尝试在我的代码中使用它:

const navigation = useNavigation();
navigation.replace('AllFriends')

但我不断收到错误消息:

Property 'replace' does not exist on type 'NavigationProp<Record<string, object | undefined>, string, NavigationState, {}, {}>'.

我也尝试过用这个

const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()
navigation.replace('route');

如此处建议:https://github.com/react-navigation/react-navigation/issues/8256

但这给了我一个错误,即替换预期的 2 个参数,但只得到 1 个...

我正在使用“@react-navigation/native”:“^5.5.1”,

javascript reactjs typescript react-native react-navigation
4个回答
11
投票

替换方法仅适用于 StackNavigators 中的屏幕。我们需要一种方法来明确键入屏幕是这样的。

实例化 StackNavigator 时,您可以传入一个类型,该类型使用路由期望接收的参数定义路由:

export type StackParams = {
   MyRoute: undefined;
   AnotherRoute: {
      id: number
   }
}

createStackNavigator<StackParams>();

然后在屏幕中将该参数列表传递给

StackNavigationProp

import { StackNavigationProp } from '@react-navigation/stack/';
import { StackParams} form 'your/routes';

const navigation =  useNavigation<StackNavigationProp<StackParams>>()
navigation.replace('route');

这样做可以确认这是一个堆栈屏幕,并提供了您可以导航到的路线列表:

replace('AnotherRoute') //success!
replace('FakeRoute') //error, this was not defined in our RouteParams

5
投票
const navigation =  useNavigation<StackNavigationProp<{route: {} }>>()
navigation.replace('route');

5
投票

如此处所述:https://github.com/react-navigation/react-navigation/issues/7820#issuecomment-689646876

最简单的方法就是这个:

const navigation = useNavigation<StackNavigationProp<ParamListBase>>();


0
投票

对于那些使用 React Native 且目前仍在使用类组件并具有标准 NavigatorParamList 设置的人

export type NavigatorParamList = {
 ...
}

export type ScreenProps = NavigationProp<NavigatorParamList>

export type ScreenComponentProps<T extends keyof NavigatorParamList> = {
  navigation: NativeStackNavigationProp<NavigatorParamList, T> // changed from navigation: NavigationProp<NavigatorParamList, T>
  route: RouteProp<NavigatorParamList, T>
}
© www.soinside.com 2019 - 2024. All rights reserved.