gpt4 book ai didi

typescript - 如何为 v5 中的嵌套导航器编写 ParamList?

转载 作者:行者123 更新时间:2023-12-04 15:32:55 25 4
gpt4 key购买 nike

假设我有两个这样的导航器:

export type RootStackParamList = {
Bootstrap: undefined;
Login: undefined;
MainApp: undefined;
};

export type MainTabsParamList = {
Explore: undefined;
Profile: undefined;
};

const MainTabs = createBottomTabNavigator<MainTabsParamList>();
const MainApp = () => (
<MainTabs.Navigator >
<MainTabs.Screen
name="Explore"
component={Explore}
/>
<MainTabs.Screen
name="Profile"
component={Profile}
/>
</MainTabs.Navigator>
);

const RootStack = createStackNavigator<RootStackParamList>();
const App = () => {
return (
<NavigationContainer>
<RootStack.Navigator initialRouteName="Bootstrap" headerMode="none">
<RootStack.Screen name="Bootstrap" component={Bootstrap} />
<RootStack.Screen name="Login" component={Login} />
<RootStack.Screen name="MainApp" component={MainApp} />
</RootStack.Navigator>
</NavigationContainer>
);
};

现在,如果我想从 Bootstrap 屏幕导航到 Profile 屏幕。我必须写:(正确注释的导航 Prop )

navigation.navigate('MainApp', {screen: 'Profile'})

但是 typescript 在这里给出了错误。说 Type '{ screen: string; }' 不可分配给类型 'undefined'。这是因为 typescript 不知道 MainApp 有子屏幕。所以我必须以某种方式编写 ParamLists 以便 typescript 知道子屏幕。我怎么做? react-navigation v5 支持吗?

最佳答案

看起来没有开箱即用的解决方案,但找到了这个 thread (issue) .在那里我们可能会找到好的solution .

type NestedNavigatorParams<ParamList> = {
[K in keyof ParamList]: undefined extends ParamList[K]
? { screen: K; params?: ParamList[K] }
: { screen: K; params: ParamList[K] }
}[keyof ParamList]

使用起来非常简单:

export type MainTabsParamList = {
Explore: undefined;
Profile: undefined;
};

export type RootStackParamList = {
Bootstrap: undefined;
Login: undefined;
MainApp: NestedNavigatorParams<MainTabsParamList>;
};

关于typescript - 如何为 v5 中的嵌套导航器编写 ParamList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60825610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com