React navigation/native 属性 在类型道具上不存在

React navigation/native property doesn't exist on type props

我在使用 TypeScript React Native 应用程序中的 React Navigation 向我的页面添加道具时遇到问题。我已尝试按照 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 {}
  }
}

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

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

type Props = StackNativeScreenProps<"Trail Screen">;

export default function TrailScreen({ trailID, navigation }: Props) {

下面是我在 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>    
  );
}

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

Property 'trailID' does not exist on type 'Props'.

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

好吧,这是我的误会。 (Read the darn documents CLOSELY!)。我正在尝试正常处理参数,就像处理任何其他组件一样。那是不正确的。当您导航到屏幕时,参数是路由的一部分。因此,您将路由放在 [normal] 参数中,然后从 route.params.

解构 [actual] 参数

所以在我的 Trails Screen 组件中,我必须这样做:

type TrailScreenProps = StackNativeScreenProps<"Trail Screen">;

export default function TrailScreen({ navigation, route }: TrailScreenProps) {
  const { trailID } = route.params;

我的 trailId 输入正确,不需要我做更多的事情。