如何以编程方式在 React Router Native 中导航?

How to programmatically navigate in React Router Native?

react-router 的 react-router-native 等价物是什么:

history = useHistory()
history.push('/new/path')

?

您可以安装 @react-navigation/native' 并创建您的 routerManage 。 使用navigation.push()方法移动

这是一个完整的例子:

app.js

 import React from 'react'
 import { StyleSheet, Text, View } from 'react-native'
 import {NavigationContainer} from '@react-navigation/native'
 import {createStackNavigator} from '@react-navigation/stack'

import Home from './pages/Home'
 import Detail from './pages/Detail'

const Stack = createStackNavigator();

 export default function App() {
  return (
   <NavigationContainer>
     <Stack.Navigator>
       <Stack.Screen name="Home" component={Home} headerMode='none'></Stack.Screen>
      <Stack.Screen name="Detail" component={Detail} headerMode='none'></Stack.Screen>
     </Stack.Navigator>
  </NavigationContainer>
   )
 }
 
 const styles = StyleSheet.create({})

home.js

 1 import React from 'react';
 2 import {StyleSheet, Text, View, Button} from 'react-native';
 3 
 4 export default function Home({navigation}) {
 5   return (
 6     <View>
 7       <Text style={styles.Title}>Home</Text>
 8       <View style={styles.Btn}>
 9         <Button
10           title="go Detail"
11           onPress={() => {
12             navigation.push('Detail',{name:'xxx'});
13           }}></Button>
14       </View>
15     </View>
16   );
17 }
18 
19 const styles = StyleSheet.create({
20   Btn: {
21     marginTop: 20,
22     width: 300,
23     height: 40,
24     left: '10%',
25   },
26   Title: {
27     color: 'red',
28     fontSize: 28,
29     textAlign: 'center',
30   },
31 });

detail.js

 1 import React from 'react';
 2 import {StyleSheet, Text, View,Button} from 'react-native';
 3 
 4 export default function Detail({route,navigation}) {
 5   const {name} = route.params;
 6   return (
 7     <View>
 8       <Text>{name}</Text>
 9       <Text style={styles.Title}>Detail</Text>
10       <View style={styles.Btn}>
11         <Button
12           title="go Home"
13           onPress={() => {
14             navigation.navigate('Home');
15           }}></Button>
16       </View>
17     </View>
18   );
19 }
20 
21 const styles = StyleSheet.create({
22   Btn: {
23     marginTop: 20,
24     width: 300,
25     height: 40,
26     left: '10%',
27   },
28   Title: {
29     color: 'red',
30     fontSize: 28,
31     textAlign: 'center',
32   },
33 });