繁体   English   中英

React Navigation w/ TypeScript:如何正确输入屏幕参数? 类型 object.ts(2339) 上不存在属性 ID

[英]React Navigation w/ TypeScript: How to properly type out screen params? Property id does not exist on type object.ts(2339)

我并没有纠结于屏幕参数的类型是如何工作的。 我查看了文档( https://reactnavigation.org/docs/typescript/ ),但我不知道他们从哪里得到 user.id。

这是我的应用程序发生的事情。 当用户点击聊天时,我正在发送聊天室的 ID。

types.tsx - 这是我添加聊天室的地方:{ id: string }

import { BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import {
  CompositeScreenProps,
  NavigatorScreenParams,
} from '@react-navigation/native';
import { NativeStackScreenProps } from '@react-navigation/native-stack';

declare global {
  namespace ReactNavigation {
    interface RootParamList extends RootStackParamList {}
  }
}

export type RootStackParamList = {
  Home: NavigatorScreenParams<RootTabParamList> | undefined;
  Modal: undefined;
  NotFound: undefined;
  ChatRoom: { id: string };
};

export type RootStackScreenProps<Screen extends keyof RootStackParamList> =
  NativeStackScreenProps<RootStackParamList, Screen>;

export type RootTabParamList = {
  TabOne: undefined;
  TabTwo: undefined;
};

export type RootTabScreenProps<Screen extends keyof RootTabParamList> =
  CompositeScreenProps<
    BottomTabScreenProps<RootTabParamList, Screen>,
    NativeStackScreenProps<RootStackParamList>
  >;

ChatRoomItem.tsx - 这是我添加 Pressable 以使用 { id: roomId } 的参数导航到“ChatRoom”的地方

interface Props {
  roomId: string;
  uri: string;
  newMessages?: number;
  name: string;
  createdAt: string;
  lastMessage: string;
}

const ChatRoomItem: React.FC<Props> = ({
  roomId,
  uri,
  newMessages,
  name,
  createdAt,
  lastMessage,
}) => {
  const navigation = useNavigation();

  const openChat = () => {
    navigation.navigate('ChatRoom', {
      id: roomId,
    });
  };

ChatRoomScreen.tsx - 这是我得到错误的地方

const ChatRoomScreen = () => {
  const route = useRoute();

  // Property 'id' does not exist on type 'object'.ts(2339)
  const roomId = route.params?.id; 

  // Logs correct roomId
  console.log(roomId); 

  return (

修复此错误的正确方法是什么? 谢谢你的帮助。 第一次在 React Native 项目中使用 TypeScript,所以我想了解这些参数类型。

您必须声明参数的类型才能将它们与 useRoute 一起使用

type ParamList = {
  Params: {id:string};
};

const { params } = useRoute<RouteProp<ParamList, 'Params'>>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM