【问题标题】:React native with typescript - how to use the useRoute from @react-navigation/native with typescript使用 typescript 反应原生 - 如何使用来自 @react-navigation/native 的 useRoute 和 typescript
【发布时间】:2020-07-08 19:17:44
【问题描述】:

我正在尝试从 route.params 获取我的 incident 对象,但我不知道如何让 typescript 识别此道具。

这是导航到我的 Detail 页面的函数,将 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()

提前致谢。

这是有错误的图像:

编辑:

我确实喜欢这样做,并且有效,但我不知道这是否正确:

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

  const incident = route.params.incident;

【问题讨论】:

    标签: typescript react-native react-navigation


    【解决方案1】:

    这太复杂了。有一种更简单的方法可以在 TS 中设置 initialParams。

    设置:

    type StackParamList = {
      TheSource: { endpoint: string; type: string;};
      BenefitDetail: React.FC;
      ItineraryMain: {reFetch: boolean;};
      Today: React.FC;
    };
    
    const Stack = createStackNavigator<StackParamList>();
    

    那么在使用的时候:

    const TheSourceRoute = (): React.ReactElement => {
      return (<StackNavigator id="TheSource" element={
        <Stack.Screen name="TheSource" component={WebviewModal} initialParams={{ endpoint: sourceUrl, type: 'directsource' }}
          options={{
            title: 'The Source',
          }}/>
      }/>
      );
    };
    

    【讨论】:

      【解决方案2】:

      您也可以根据您想要的 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
      >;
      

      用法:

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

      【讨论】:

      • 救了我的命。谢谢!
      【解决方案3】:

      昨天刚做的!

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

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

      然后你在RouteProp中使用那个参数和屏幕名称:

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

      这里是解释这一切的文档https://reactnavigation.org/docs/typescript

      【讨论】:

        猜你喜欢
        • 2018-11-03
        • 1970-01-01
        • 2021-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多