React Native Stack Navigation With Class Component

Que*_*123 3 reactjs react-native react-navigation

I am currently building a react native app and am using a stack navigator to navigate between the screens in my app. In my App.js, I am currently storing the screens in this format:

const Stack = createStackNavigator();

export default function App() {
  return (
      <NavigationContainer>
        <Stack.Navigator initialRouteName="screen1">
          <Stack.Screen name="screen1" component={Screen1}></Stack.Screen>
          <Stack.Screen name="screen2" component={Screen2}></Stack.Screen>
        </Stack.Navigator>
      </NavigationContainer>
  );
}
Run Code Online (Sandbox Code Playgroud)

After the user is in screen 1, I want to be able to navigate to screen 2 on the press of a button. I read through the documentation and I only saw examples on how to do this with functional components, for example:

function Screen1({ navigation }) {
  return (
    <View>
      <Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
    </View>
  );
}
Run Code Online (Sandbox Code Playgroud)

But how can I do this with a class component:

class Screen1 extends Component {

    render() {
        return(
            <View>
               // This does not work because I do not know how to pass in the navigation object
               <Button title="Go to Home" onPress={() => navigation.navigate('screen2')} />
            </View>
        )
    }
}
Run Code Online (Sandbox Code Playgroud)

Where do I pass in the { navigation } ?

Gur*_*ran 10

您不必传递导航,它作为道具传递。

您可以像下面一样访问它

this.props.navigation.navigate('nextScreen')
Run Code Online (Sandbox Code Playgroud)

  • 你有一个错误,它应该是这样的:`this.props.navigation.navigate('nextScreen')` (2认同)