웹, 앱 개발/RN React-Native

[React Native] React Navigation - Stack Navigation 화면 전환

나아가는중 2021. 1. 23. 00:21
반응형

React Native React Navigation - Stack Navigation 화면 전환

 

지난번 포스트에서 React Navigation중에서 Stack Navigation을 등록하는 방법에 대해 설명드렸습니다,

이번에는 Stack Navigation간 화면 전환 방법에 대해 설명드리겠습니다.

 

우선 사용하실 스크린(Screen)들을 NavigationContainer > Stack.Navigator 안에 등록해주셔야 합니다.

저는 따로 screens 폴더를 만들어 그곳에 screen으로 사용할 js파일을 등록해주었기 때문에 import로 가져와서 사용해주었습니다,

 

React functional component hooks 를 사용한 방법입니다,

 

App.js

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import React from 'react';
import Main from './screens/Main';
import Screen from './screens/Login'


const Stack = createStackNavigator();

const App = () => {
    return(
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen name="Main" component={Main}/>
                <Stack.Screen name="Login" component={Screen}/>
            </Stack.Navigator>
        </NavigationContainer>
    )
}

export default App;

Main.js

import React from 'react';
import { View, StyleSheet, Text, Button } from 'react-native';

const Main = ({ navigation }) => {

    return(
        <View style={styles.container}>
            <Text> Main Screen </Text>
            <Button 
                title={"Go to Login Screen"}
                onPress={() => {navigation.navigate('Login')}}
            />
        </View>
    )
}

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

export default Main;

여기에서 버튼을 누르면 Login 페이지로 이동하게 하였습니다.

 

Login.js

import React from 'react';
import { View, StyleSheet, Text } from 'react-native';

const Login = ( ) => {
    
    return (
        <View style={styles.container}>
            <Text> Login Page </Text>
        </View>
    )
}

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

export default Login;

 

이제 Main screen에서 버튼으로 Login screen으로 이동하는 화면 전환이 가능해집니다.

반응형