React Native with typescript - 如何使用来自@react-navigation/native 的 useRoute with typescript

Chr*_*ado 15 typescript react-native react-navigation

我正在尝试从中获取我的事件对象,route.params但我不知道如何让打字稿识别此道具。

这是导航到我的详细信息页面的函数,将事件传递给参数:

const navigateToDetail = (incident: IncidentProps): void => {
    navigation.navigate('Detail', { incident });
  };
Run Code Online (Sandbox Code Playgroud)

这是我尝试从 route.params 获取此对象的详细信息页面代码的一部分:

type IncidentRouteParams = {
  incident: IncidentProps;
}

const Detail: React.FC = () => {
  const navigation = useNavigation();
  const route = useRoute();

  const incident = route.params.incident;
Run Code Online (Sandbox Code Playgroud)

我想我需要以某种方式将这个IncidentRouteParams类型传递给const route = useRoute()

提前致谢。

这是带有错误的图像:

编辑:

我确实喜欢这个,并且它有效,但我不知道它是否是正确的方法:

  const route = useRoute<RouteProp<Record<string, IncidentRouteParams>, string>>();

  const incident = route.params.incident;
Run Code Online (Sandbox Code Playgroud)

小智 23

昨天刚做的!

TLDR:首先,您需要使用每个屏幕名称及其接收的参数定义一个类型:

type ParamList = {
  Detail: {
    incident: IncidentProps;
  };
};
Run Code Online (Sandbox Code Playgroud)

然后您使用该参数和屏幕名称RouteProp

const route = useRoute<RouteProp<ParamList, 'Detail'>>();
Run Code Online (Sandbox Code Playgroud)

以下是解释所有这些的文档https://reactnavigation.org/docs/typescript


小智 15

您还可以根据所需的 ParamList 创建一个类型,因此您只需将该类型导入到组件中并将 RouteName 作为参数传递即可。

import { RouteProp } from '@react-navigation/native';

export type RootStackParamList = {
  Home: undefined;
  Feed: { sort: 'latest' | 'top' };
};

export type RootRouteProps<RouteName extends keyof RootStackParamList> = RouteProp<
  RootStackParamList,
  RouteName
>;
Run Code Online (Sandbox Code Playgroud)

用法:

export const Feed = () => {    
    const route = useRoute<RootRouteProps<'Feed'>>();
    return <Text>{route.params.sort}</Text>
}
Run Code Online (Sandbox Code Playgroud)