【问题标题】:React Navigation Error - TypeScript - This Expression Is Not Callable反应导航错误-TypeScript-此表达式不可调用
【发布时间】:2021-02-12 00:15:02
【问题描述】:

我正在尝试为升级到 React Navigation 5 时遇到的这个打字稿问题找到最佳实践。我遇到的错误是

This expression is not callable.
  Each member of the union type '{ <RouteName extends "Stack1Screen1" | "Home">(...args: 
undefined extends SampleParamList1[RouteName] ? [RouteName] | [RouteName, 
SampleParamList1[RouteName]] : [...]): void; <RouteName extends "Stack1Screen1" | 
"Home">(route: { ...; } | { ...; }): void; } | { ...; }' has signatures, but none of those 
signatures are compatible with each other.ts(2349)

这是我基本上使用的代码:

import { StackScreenProps } from '@react-navigation/stack';

export type SampleParamList1 = {
  Stack1Screen1: undefined;
  Home: undefined;
};
export type SampleParamList2 = {
  Stack2Screen2: undefined;
  Home: undefined;
};

type Props =
  | StackScreenProps<SampleParamList1, 'Stack1Screen1'>
  | StackScreenProps<SampleParamList2, 'Stack2Screen2'>;

const ThisScreen: React.FC<Props> = ({ navigation, route }) => {
  const navToHome = () => navigation.navigate('Home');
};

将鼠标悬停在navigation.navigate('Home') 函数上会显示错误消息。 关于如何解决这个问题的任何想法?谢谢! :)

【问题讨论】:

  • 在导航堆栈中使用两种不同的类型来描述屏幕道具是什么意思?为什么不能简单地合二为一?

标签: reactjs typescript react-native react-navigation react-navigation-v5


【解决方案1】:

我用过这样的东西。

export type RandomParamList = {
    ScreenRandom1: undefined;
    ScreenRandom2: undefined | { screen: string }; // arguments
    ScreenRandom3: undefined | { screen?: string, params: { param1: string } };
} ;
export type HomeParamList = {
    HomeScreen1: undefined;
    HomeScreen2: undefined | { screen: string };
    HomeScreen3: undefined | { screen?: string, params: { param1: string } };
    HomeScreen4: undefined;
    HomeScreen5: undefined | { screen: string };
} & RandomParamList;

export type HomeNavProps<T extends keyof HomeParamList> = {
    navigation: StackNavigationProp<HomeParamList, T>;
    route: RouteProp<HomeParamList, T>;
};

const ThisScreen: React.FC<HomeNavProps> = ({ navigation, route }) => {
  const navToHome = () => navigation.navigate('HomeScreen1');
const navToHome = () => navigation.navigate('Home'); // you will get error that Home is not allowed
};

【讨论】:

    猜你喜欢
    • 2020-08-16
    • 2021-06-12
    • 2021-04-27
    • 1970-01-01
    • 2022-09-30
    • 2021-05-05
    • 1970-01-01
    • 2021-05-17
    • 2021-02-21
    相关资源
    最近更新 更多