【问题标题】:How to define routes types in React Navigation stack?如何在 React Navigation 堆栈中定义路由类型?
【发布时间】:2021-07-30 07:59:17
【问题描述】:

我需要在堆栈中定义路由类型(而不是在组件中),我知道您可以在组件本身中使用 RouteProp 来做到这一点,但我只是不知道如何在堆栈上应用它。

<Stack.Screen
    name="MarketAssetDetailsPage"
    options={({ route }) =>
      HeaderWithBackTitle({
        title: `${route.params.routeName} Market Details`,
        bgColor: route.params.data.assetColor,
        textColor: 'white',
      })
    }
    component={MarketAssetDetailsPage}
  />

这里我有一个屏幕接收 routeName 和一个数据。 Eslint 和 typescript 在这里抱怨,如何在这里定义类型?谢谢。

【问题讨论】:

    标签: javascript reactjs react-native react-navigation


    【解决方案1】:

    你应该为道具创建一个类型。

    export type StackParamList = {
      MarketAssetDetailsPage: {
        routeName: string,
        data: any // Change to be the type of data.
      }
    }
    

    在你的组件内部你可以做这样的事情

    import { StackNavigationProp } from '@react-navigation/stack';
    
    type NavigationProps = StackNavigationProp<StackParamList, 'MarketAssetDetailsPage'>;
    
    interface Props {
      navigation: NavigationProps
    }
    
    const MarketAssetDetailsPage = ({ navigation }: Props) => {
    
    }
    

    React Navigation 网站上有一个很好的 TypeScript 支持指南 - https://reactnavigation.org/docs/typescript/

    【讨论】:

    • 所以如果我在组件上定义,我也可以在堆栈上看到它吗?因为这就是问题所在
    猜你喜欢
    • 2019-06-19
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2020-11-07
    • 2021-01-24
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    相关资源
    最近更新 更多