React-Native | Native Stack Navigator

duroomi·2023년 1월 7일
0

Native Stack Navigator

React Navigation의 하위 라이브러리로 모바일 스크린 상단(헤더 부분)에서 스크린(컴포넌트)간의 이동을 도와주는 라이브러리이다.

사용하기 위해서 터미널에 아래 명령어를 입력하여 우선적으로 설치한다.

npm install @react-navigation/native-stack

또는

yarn add @react-navigation/native-stack

그리고 import하고 변수에 할당해주어야 한다.

import { createNativeStackNavigator } from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();

function MyStack() {
  return (
    // Stack.Navigator로 감싸준다.
    <Stack.Navigator>
    // Stack.Screen의 속성으로 name, comopent가 있는데
    // name은 해당 스크린의 이름을, comonent에는 해당 스크린의 컴포넌트명을 적어준다.
      <Stack.Screen name="Home" component={Home} />
      <Stack.Screen name="Notifications" component={Notifications} />
      <Stack.Screen name="Profile" component={Profile} />
      <Stack.Screen name="Settings" component={Settings} />
    </Stack.Navigator>
  );
}

그리고 Stack.Screen의 하위 컴포넌트에는 기본적으로 Navigation이라는 prop을 가진다. Navigation에서 goBack, navigate등 여러 유용한 기능들을 구조분해할당으로 꺼내서 사용할 수 있다. 아래 예시를 보자.

import { Text, TouchableOpacity, View } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";

// stack navigator를 활용하기 위해서 변수에 할당한다.
const Stack = createNativeStackNavigator();

export default function App() {

  // Stack.Screen 아래에 있는 컴포넌트들은 기본적으로 navigation이라는 prop을 가진다.
  // navigation 아래 navigate, goBack 등을 이용해보자.
  const One = ({navigation: {navigate}}) => {
    return (
      <View>
        {/* Two 컴포넌트로 이동 가능하다. */}
        <TouchableOpacity onPress={()=>navigate("Two")}>
          <Text>Go to Two</Text>
          </TouchableOpacity>
      </View>
    );
  };

  const Two = ({navigation: {navigate}}) => {
    return (
      <View>
        {/* Three 컴포넌트로 이동 가능하다. */}
        <TouchableOpacity onPress={()=>navigate("Three")}>
          <Text>Go to Three</Text>
          </TouchableOpacity>
      </View>
    );
  };

  const Three = ({navigation: {goBack}}) => {
    return (
      <View>
        {/* Two 컴포넌트로 '뒤로가기' 한다. */}
        <TouchableOpacity onPress={()=>goBack()}>
          <Text>Go Back</Text>
          </TouchableOpacity>
      </View>
    );
  };

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="One" component={One} />
        <Stack.Screen name="Two" component={Two} />
        <Stack.Screen name="Three" component={Three} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

아래 공식 문서를 참고하면 더 많은 navigation props를 이용할 수 있다.

https://reactnavigation.org/docs/navigation-prop

profile
🙋‍♂️즐겁게 개발하기! 📚나의 지식 보관함!

0개의 댓글