【问题标题】:Typescript StackNavigatonProps and Screen props in react-navigation v5react-navigation v5 中的 Typescript StackNavigatonProps 和 Screen 道具
【发布时间】:2020-06-27 11:13:09
【问题描述】:

当屏幕位于路由器的不同文件中时,为屏幕的navigation 属性定义类型的最佳方法是什么?假设我有一个文件,我在其中定义了路由:

//Router.tsx

type RootStackParamList = {
  Home: undefined;
  Profile: undefined;
}

const Stack = createStackNavigator<RootStackParamList>();

// Component rendering navigator
const Router = () => {
   .
   .
   .
}

然后我有屏幕的单独文件:

// Home.tsx


// here has to be the same RootStackParamList
// that we've already defined in Router.tsx
type = HomeScreenNavigationProp = StackNavigationProp<
  RootStackParamList,
  "Home"
>;

type Props: {
  navigation: HomeScreenNavigationProp
}


const Home = ({navigation}: Props) => {
  .
  .
  .
}

我是否必须将RootStackParamList 一遍又一遍地复制到每个屏幕,或者创建类似types.ts 的文件并从那里导入?有没有更好的处理方法?我几乎在每个组件中都使用navigation

【问题讨论】:

    标签: typescript react-native react-navigation expo


    【解决方案1】:

    你可以试试这个:

    type RootStackComponent<RouteName extends keyof RootStackParamList> = React.FC<
      navigation: StackNavigationProp<RootStackParamList, RouteName>,
      route: RouteProp<RootStackParamList, RouteName>
    >
    
    const Home: RootStackComponent<'Home'> = ({ navigation, route }) => {}
    

    【讨论】:

    • 这个语法正确吗?我收到“逗号运算符的左侧未使用且没有副作用”错误
    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2021-10-21
    相关资源
    最近更新 更多