[英]React Navigation w/ TypeScript: How to properly type out screen params? Property id does not exist on type object.ts(2339)
I'm not wrapping my head around how the types work for screen params.我并没有纠结于屏幕参数的类型是如何工作的。 I looked at the documentation ( https://reactnavigation.org/docs/typescript/ ) but I have no idea where they got the user.id from.
我查看了文档( https://reactnavigation.org/docs/typescript/ ),但我不知道他们从哪里得到 user.id。
Here is what is going on with my application.这是我的应用程序发生的事情。 I'm sending the id of the chat room when a user clicks on a chat.
当用户点击聊天时,我正在发送聊天室的 ID。
types.tsx - This is where I added my ChatRoom: { id: string } 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 - This is where I add the Pressable to navigate to 'ChatRoom' with the params of { id: roomId } 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 - This is where the I am getting the error 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 (
What is the proper way of fixing this error?修复此错误的正确方法是什么? Thanks for your help.
谢谢你的帮助。 First time using TypeScript with a React Native project so I want to understand these param types.
第一次在 React Native 项目中使用 TypeScript,所以我想了解这些参数类型。
You have to declare the type of your param in order to use them with useRoute您必须声明参数的类型才能将它们与 useRoute 一起使用
type ParamList = {
Params: {id:string};
};
const { params } = useRoute<RouteProp<ParamList, 'Params'>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.