react-navigation:从标题中的按钮导航到不同的屏幕

par*_*sai 5 react-native react-navigation

我的标题右侧有一个图标,按下该按钮后,我想导航到不同的屏幕。

我对此进行了大量搜索,但所有解决方案都是针对类组件的,并且没有可用的官方文档。

我正在使用本机版本 0.61.4。

在按下右侧标题中的图标时,我想移动“ProfileScreen”。所有其他导航工作正常。我在“HomeScreen”中有一个按钮可以移动到“ResultsScreen”,但无法从标题转到“ProfileScreen”。

这是我的代码片段

const Stack = createStackNavigator();

const App = () => {
    return (
        <SafeAreaView style={{ flex: 1 }}>
            <NavigationContainer>
                <Stack.Navigator>
                    <Stack.Screen 
                        name="Home" 
                        component={HomeScreen}
                        options={
                            {
                                title: 'Home',
                                headerStyle: {
                                    backgroundColor: '#273469',
                                },
                                headerTintColor: '#EBF2FA',
                                headerRight: () => (
                                    <Icon
                                      onPress={() => navigate('ProfileScreen')}
                                      name="edit"
                                      type="material"
                                    />
                                ),
                            }
                        }
                    />
                    <Stack.Screen 
                        name="ResultsScreen" 
                        component={ResultsScreen}
                    />
                    <Stack.Screen 
                        name="ProfileScreen"
                        component={ProfileScreen}
                    />
                </Stack.Navigator>
            </NavigationContainer>
        </SafeAreaView>
    )
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*off 8

options可以接受一个函数作为参数,这个函数接受props一个参数。

这是文档

这是用于信息的 TypeScript 定义:

     * Navigator options for this screen.
     */
    options?: ScreenOptions | ((props: {
        route: RouteProp<ParamList, RouteName>;
        navigation: any;
    }) => ScreenOptions);
Run Code Online (Sandbox Code Playgroud)

如您所见,道具包含navigation可用于调用导航的对象,如下所示:

 options={({ navigation }) => ({
              title: 'Home',
              headerStyle: {
                backgroundColor: '#273469',
              },
              headerTintColor: '#EBF2FA',
              headerRight: () => (
                <Icon
                  onPress={() => navigation.navigate('ProfileScreen')}
                  name="edit"
                  type="material"
                />
              ),
            })}
Run Code Online (Sandbox Code Playgroud)