如何从一个堆栈屏幕导航到另一个堆栈屏幕?

时间:2020-04-14 15:56:58

标签: react-native react-navigation-v5

//Navigator2.js

function Navigator2() {
  return (
    <Navigator2Stack.Navigator
      headerMode="screen"
      screenOptions={{
        headerTintColor: "white",
        headerStyle: { backgroundColor: "#1c5e74" },
      }}
    >
      <Navigator2Stack.Screen
        name="Screen2"
        component={Screen2.js}
        options={{
          title: "Screen2",
        }}
      />
    </Navigator2.Navigator>
  );
}
export default Navigator2;


//Screen1.js(which is registered in Navigator1 stack)

export const Screen1 = ({navigation}) => {
  return (
    <View style={styles.screen}>
      <Text>Screen1!</Text>
      <Button
        title="go to Screen2"
        onPress={() => navigation.navigate('Navigator2')}
      ></Button>
    </View>
  );
};

the folder structure goes like this-->
Navigation Folder
      |-->Navigator1.js
      |-->Navigator2.js
screens
   |-->Screen1.js

在Navigator1的堆栈中被搅乱的Screen1.js文件和在Navigator2中的屏幕,我想从Screen1导航到Screen 2,我该怎么做?

我正在使用React Navigation v5。

1 个答案:

答案 0 :(得分:0)

经过一些研究,这应该可以完成工作:

<Button
    title="go to Screen2"
    onPress={() => navigation.navigate('Navigator2', { screen: 'Screen2' })}
/>

编辑:

这是一个完整的例子:

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

const Screen1 = ({ navigation }) => (
    <View style={styles.component}>
        <Button title="Go to Screen 2" onPress={() => navigation.navigate('Navigator2', { screen: 'Screen2' })} />
    </View>
)

const Screen2 = ({ navigation }) => (
    <View style={styles.component}>
        <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
)

const Navigator1 = createStackNavigator()

const Nav1 = () => (
    <Navigator1.Navigator>
        <Navigator1.Screen name="Screen1" component={Screen1} />
    </Navigator1.Navigator>
)

const Navigator2 = createStackNavigator()

const Nav2 = () => (
    <Navigator2.Navigator>
        <Navigator2.Screen name="Screen2" component={Screen2} />
    </Navigator2.Navigator>
)

const Main = createStackNavigator()

export default props => (
    <NavigationContainer>
        <Main.Navigator headerMode="none">
            <Main.Screen name="Navigator1" component={Nav1} />
            <Main.Screen name="Navigator2" component={Nav2} />
        </Main.Navigator>
    </NavigationContainer>
)

const styles = StyleSheet.create({
    component: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    }
})