TypeScript 中的 React Navigation navigation.navigate("SomeScreen") 错误

Dav*_*ord 5 javascript typescript react-native react-navigation

使用 TypeScript 时出现的一个常见错误react-navigation是:

“string”类型的参数不可分配给“{ key: string;”类型的参数 参数?:未定义;合并?:布尔值 | 不明确的; } | { 名称:从不;键?: 字符串 | 不明确的; 参数:从不;合并?:布尔值 | 不明确的; }'

这可能是由什么引起的?

Dav*_*ord 8

当尚未定义特定屏幕的类型时会发生这种情况。

我将描述堆栈导航的设置类型、钩子中的使用useNavigation以及将{navigation}through 属性传递到屏幕。

首先,设置堆栈导航器

/**
* Types for Stack Navigator.
*/
export type StackParamList = {
  Main: undefined;
  Home: undefined;
};

const Stack = createStackNavigator<StackParamList>();
Run Code Online (Sandbox Code Playgroud)

使用useNavigation钩子时:

import { StackNavigationProp } from "@react-navigation/stack";

/**
 * Types for the Stack Navigator.
 */
export type StackNavigation = StackNavigationProp<StackParamList>;

const navigation = useNavigation<StackNavigation>();
Run Code Online (Sandbox Code Playgroud)

当将导航作为屏幕中的 prop 向下传递时:

/**
 * Types for passing the navigation props to screens in the Stack Navigator.
*/
export type StackNavigationProps = {
  navigation: StackNavigation;
};

const SomeScreenInTheStack = ({ navigation }: StackNavigationProps) => {
...
}
Run Code Online (Sandbox Code Playgroud)

我在另一个问题中扩展了答案,就像这样,但发现OP没有正确标记帖子,所以我创建了这个问答。

希望这对某人有用!