如何在react-navigation v5中使用嵌套导航时编写类型定义

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

我有类似this document的类型定义,但是在使用嵌套导航时会出现问题。

示例代码在这里:

在我的App.tsx

export type MainStackParamList = {
  Setting: undefined
}
export type TabParamList = {
  Home: undefined
  Personal: undefined
}
const MainStack = createNativeStackNavigator<MainStackParamList>()
const Tab = createBottomTabNavigator<TabParamList>()
const RootStack = createNativeStackNavigator()

const MainStackScreen = () => (
  <MainStack.Navigator screenOptions={{ headerShown: false }}>
    <MainStack.Screen name="Setting" component={Setting} />
  </MainStack.Navigator>
)

const TabScreen = () => (
  <Tab.Navigator screenOptions={{ headerShown: false }}>
    <Tab.Screen name="Home" component={Setting} />
    <Tab.Screen name="Personal" component={Setting} />
  </Tab.Navigator>
)

const RootStackScreen = () => (
  <RootStack.Navigator screenOptions={{ headerShown: false }}>
    <RootStack.Screen name="Tab" component={TabScreen} />
    <RootStack.Screen name="Main" component={MainScreen} />
  </RootStack.Navigator>
)

Home.tsx

type HomeRouteProp = RouteProp<TabParamList, 'Home'>
type HomeNavigationProp = CompositeNavigationProp<
  BottomTabNavigationProp<TabParamList, 'Home'>,
  NativeStackNavigationProp<MainStackParamList>
>
type Props = {
  route: HomeRouteProp
  navigation: HomeNavigationProp
}

 // ...

 navigation.navigate('Main', { screen: 'Setting' })

并且打字稿说不能将'Main'分配给'Home'| “个人” | '设置'

react-native react-navigation react-navigation-stack
1个回答
0
投票

您还需要为根堆栈添加类型。

type RootStackParamList = {
  Tab: undefined;
  Main: undefined;
}

然后为您的导航道具:

// Navigation prop for your MainStack
type MainNavigationProp = CompositeNavigationProp<
  NativeStackNavigationProp<MainStackParamList, 'Setting'>,
  NativeStackNavigationProp<RootStackParamList>
>

// Navigation prop for your Home
type HomeNavigationProp = CompositeNavigationProp<
  BottomTabNavigationProp<TabParamList, 'Home'>,
  MainNavigationProp
>

使用CompositeNavigationProp组合导航道具取决于嵌套。在这里,您的Home屏幕嵌套在MainStack内部,因此其导航道具需要与MainStack的导航道具结合使用。


上一个答案:

在堆栈中,您有Setting,在选项卡中,您有HomePersonalMain的任何地方都没有定义,因此错误是正确的。

[好像您的Main是您的MainStack,我想您是在选项卡中呈现的?然后您需要在Main: undefined

中添加TabParamList
© www.soinside.com 2019 - 2024. All rights reserved.