React native with typescript-如何通过@ react-navigation / native使用typescript使用useRoute

问题描述 投票:0回答:1

我正在尝试从route.params获取我的incident对象,但我不知道如何使打字稿识别该道具。

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

const navigateToDetail = (incident: IncidentProps): void => {
    navigation.navigate('Detail', { incident });
  };

并且这是“详细信息”页面代码的一部分,在这里我尝试从route.params获取此对象:

type IncidentRouteParams = {
  incident: IncidentProps;
}

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

  const incident = route.params.incident;

我想我需要将此IncidentRouteParams类型传递给const route = useRoute()

提前感谢。

Here is the image with the error

编辑:

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

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

  const incident = route.params.incident;
typescript react-native react-navigation
1个回答
0
投票

昨天刚做过!

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

type ParamList = {
  Detail: {
    incident: IncidentProps;
  };
};

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

const route = useRoute<RouteProp<ParamList, 'Detail'>>();

这里是解释所有https://reactnavigation.org/docs/typescript的文档>

© www.soinside.com 2019 - 2024. All rights reserved.