본문 바로가기

Study/React

[React Native] 다른 화면으로 전환하기

다른 화면으로 넘어가는 것, 장면전환 예시이다.

 

// App.tsx

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { View } from "react-native";
import DetailScreen from "./src/screens/DetailScreen";
import HomeScreen from "./src/screens/HomeScreen";

/*
    npm install react-native-gesture-handler
    npm install @react-navigation/native
    npm install @react-navigation/native-stack
    npm install react-native-safe-area-context
    npm install react-native-screens
    npm install watcher (배포 중 오류 발생시)
*/

const Stack = createNativeStackNavigator();

export default function App() {

  return (
    <NavigationContainer>
      {/* 처음 접속시 initialRouteName에 지정된 경로에서 열림 */}
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Detail" component={DetailScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  )
}

 

화면 1(홈화면)

 

// HomeScreen.tsx

import { useNavigation } from "@react-navigation/native";
import React from "react";
import { Button, StyleSheet, Text, View } from "react-native";

export default function HomeScreen() {

    // 어떤 뷰로든 이동할 수 있다.
    const navi = useNavigation();

    return (
        <View style={styles.container}>
            <Text>여기는 HomeScreen 입니다.</Text>
            {/* onPress에 App.tsx에서 지정한 이름을 넣어준다. */}
            <Button title="Detail로 이동" onPress={() => navi.navigate("Detail")} />
        </View>
    )
}

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

 

 

화면 2 (디테일 화면)

 

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

export default function DetailScreen() {

  return (
    <View style={styles.container}>
        <Text>여기는 DetailScreen 입니다.</Text>
    </View>
    )
}

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