如何在 React Navigation 中使用标题按钮导航到其他页面?

Cam*_*ile 3 react-native react-navigation

如何使用标题上的按钮在屏幕之间导航?当我尝试使用标题按钮返回或导航到其他页面时,我收到相同的错误。屏幕上的按钮运行良好。

“未定义不是一个对象(评估‘navigation.navigate’)(设备)”

“未定义不是一个对象(评估‘navigation.goBack’)”

import 'react-native-gesture-handler';
import  React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import Constants from 'expo-constants';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

//Screen 1
function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}

//Screen 2
function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details</Text>
      <Button title="back home" onPress={() => navigation.goBack()} />
    </View>
  );
}

export default function App({ navigation, route }) {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRout="Home">
        <Stack.Screen name="Home" component={HomeScreen} />


        <Stack.Screen
          name="Details"
          component={DetailsScreen}
          options={{
            headerTitle: () => <Text>Register</Text>,
            headerRight: () => <Button title="Test" onPress={() => navigation.navigate('Home')} />,
            headerLeft: () => <Button title="back home" onPress={() => navigation.goBack()} />,
          }}
        />


      </Stack.Navigator>
    </NavigationContainer>
  );
}
Run Code Online (Sandbox Code Playgroud)

https://snack.expo.io/@camileppst/navigation-test

Wen*_*n W 7

您需要注入导航道具,而不是从应用程序组件的道具中获取它:

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRout="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen
          name="Details"
          component={DetailsScreen}
          options={({navigation}) => ({
            headerTitle: () => <Text>Register</Text>,
            headerRight: () => <Button title="Test" onPress={() => navigation.navigate('Home')} />,
            headerLeft: () => <Button title="back home" onPress={() => navigation.goBack()} />,
          })}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}
Run Code Online (Sandbox Code Playgroud)