TIL.React Navigation(RN)

chloe·2021년 3월 19일
0

React Native

목록 보기
2/3
post-thumbnail

Stack Navigator

react navigation의 stack navigator는 navigation history를 관리하고 스크린 간의 이동을 할 수 있게 해준다.
가장 많이 쓰이는 navigator로는 createStackNavigator가 있다.

yarn add @react-navigation/stack

CreateStackNavigator

CreateStackNavigator는 2개의 프로퍼티 ScreenNavigator를 포함하는 객체를 리턴하는 함수다.
Navigator는 자식 element로 screen을 포함해야한다.

NavigationContainer는 navigation tree를 관리하고 navigation 상태를 포함하는 컴포넌트다. 보통은 App의 root에서 이 컴포넌트를 렌더한다.

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

function HomeScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

모든 route 구성은 navigator의 props로 명시된다.
stack navigator에 2번째 screen을 추가해보고 첫번째로 render하기 위한 Home Screen을 구성해보자

function DetailsScreen() {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

이제 stack은 2개의 route(Home,Details)를 가진다.

Options

navigator의 각 스크린들은 몇개의 옵션들을 명시할 수 있다. 예를들면 header에 render하기 위한 타이틀을 설정할 수 있다. 이러한 옵션들은 screen component를 위한 options prop으로 전달할 수 있다.

<Stack.Screen
  name="Home"
  component={HomeScreen}
  options={{ title: 'Overview' }}
/>

때때로, navigator의 모든 스크린에 같은 옵션을 주고 싶을 때가 있다. 이 경우에는 navigator에 screenOptionsprop을 전달하면 된다.

참고:https://reactnavigation.org/docs/hello-react-navigation

profile
Front-end Developer 👩🏻‍💻

0개의 댓글