反应导航/本机属性在类型道具上不存在

Chi*_*hip 5 typescript react-native react-navigation expo

我在使用 TypeScript React Native 应用程序中的 React Navigation 将 prop 添加到页面时遇到问题。我尝试按照https://reactnavigation.org/docs/typescript中的说明进行操作,特别是组织类型部分,并创建了一个 navigationTypes.tsx 文件:

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

export type StackParamList = {
  Home: undefined;
  Admin: undefined;
  "Trail Screen": { trailID: number } | undefined;
};

export type StackNativeScreenProps<T extends keyof StackParamList> =
  NativeStackScreenProps<StackParamList, T>;

declare global {
  namespace ReactNavigation {
    interface ParamList extends StackParamList {}
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我在 Trail Screen 组件中调用的内容:

import { StackNativeScreenProps } from "../interfaces/navigationTypes";

type Props = StackNativeScreenProps<"Trail Screen">;

export default function TrailScreen({ trailID, navigation }: Props) {
Run Code Online (Sandbox Code Playgroud)

以下是我在 App.tsx 中调用导航的方式:

const Stack = createNativeStackNavigator<StackParamList>();

function App() {
  return (
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={HomeScreen} />
          <Stack.Screen name="Admin" component={AdminLogin} />
          <Stack.Screen name="Trail Screen" component={TrailScreen} />
        </Stack.Navigator>
      </NavigationContainer>    
  );
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试在导航器中添加选项或任何内容,它只会给我更多相同的错误:

类型“Props”上不存在属性“trailID”。

我的主页和管理屏幕使用导航道具可以正常工作。当我尝试添加可选道具时,我只是不确定出了什么问题。

Chi*_*hip 5

好吧,所以这是我的一个误解。(仔细阅读该死的文件!)。我正在尝试正常对待参数,就像对待任何其他组件一样。这是不正确的。当您导航到屏幕时,参数是路线的一部分。因此,您将路线放入 [正常] 参数中,然后从 中解构 [实际] 参数route.params

因此,在我的 Trails Screen 组件中,我必须这样做:

type TrailScreenProps = NativeStackScreenProps<"Trail Screen">;

export default function TrailScreen({ navigation, route }: TrailScreenProps) {
  const { trailID } = route.params;
Run Code Online (Sandbox Code Playgroud)

我的trailId输入正确,不需要我再做任何事情。