我应该如何定义反应导航提供的道具类型?

How should I define type of props supplied by react-navigation?

我有一个 react native 应用程序,其中定义了 navigation 堆栈:

 <Stack.Navigator
            initialRouteName={NavigationLocations.SIGNUP}
            ...
            }}>
           ...
            <Stack.Screen
                name={NavigationLocations.SHEET}
                component={Sheet}
                options={
                    {
                        title: "Character sheet",
                        headerLeft: null
                    }}
            />
        </Stack.Navigator>

这是我的navigation props定义:

export type RootStackParamList = {
    Signup: undefined,
    Login: undefined,
    Dashboard: undefined,
    SheetView: {sheet: ISheet}
};

我应该如何在接收导航传递的 sheet 对象的组件中定义 sheet 道具?

type Props = StackScreenProps<RootStackParamList, NavigationLocations.SHEET>

export default function Sheet({sheet}: Props) {
    const sheet = props.route.params.sheet;

目前我收到这个错误:Error:(11, 32) TS2339: Property 'sheet' does not exist on type 'StackScreenProps<RootStackParamList, NavigationLocations.SHEET>'.

我正在使用 NavigationLocations 枚举,因为我通常不喜欢使用字符串作为标识符,但我认为我的实现在这里引入了错误。我做错了什么?

StackScreenProps 只包括道具 navigationroute 的类型。

type Props = {
    navigation: StackNavigationProp<RootStackParamList, NavigationLocations.SHEET>;
    route: Route<NavigationLocations.SHEET, {
        ...;
    }>;
}

您似乎已尝试将 sheet 作为顶级道具访问:

function Sheet({sheet}: Props) {

也作为嵌套 属性:

const sheet = props.route.params.sheet;

第二个是正确的。如果这样做,我们可以取消一些嵌套级别:

export default function Sheet({ navigation, route }: Props) {
  // sheet has type ISheet
  const {sheet} = route.params;

只要枚举的值与 RootStackParamList 中的键匹配,枚举应该不是问题。当它不匹配时,我会得到一个不同的错误,所以这不是你的问题。