HelloMinchan
처음처럼
HelloMinchan
LinkedIn
전체 방문자
오늘
어제
  • 분류 전체보기 (306)
    • Backend (4)
      • NestJS (1)
      • Express (1)
      • Spring (2)
    • Infrastructure (1)
      • AWS (1)
    • Frontend (1)
      • Next.js (1)
    • Language & Runtime (4)
      • Java (2)
      • Node.js (2)
    • Computer Science (8)
      • Computer Networks (3)
      • Operating Systems (4)
      • OOP (1)
    • 독서 (4)
      • 데이터 중심 애플리케이션 설계 (3)
      • 객체지향의 사실과 오해 (1)
    • 회고 (4)
      • Project (2)
      • Career (2)
    • Deprecated (280)

채널

  • GitHub
  • LinkedIn

최근 글

태그

  • 알고스팟Python
  • programmers
  • Database
  • 개발자
  • 데이터베이스
  • 프로그래머스Python
  • front-end
  • back-end
  • Baekjoon Online Judge
  • 백준Go
  • 백준C++
  • 프로그래머스C++
  • 프로그래밍
  • 코딩
  • 백준Python
  • 백준
  • 프로그래머스
  • 백엔드
  • 알고스팟
  • Algospot

최근 댓글

인기 글

hELLO
HelloMinchan

처음처럼

[React Native] React Navigation 설치 및 사용법
Deprecated

[React Native] React Navigation 설치 및 사용법

2020. 2. 7. 23:29

Copyright © 2020 Facebook Inc.

[React Native] React Navigation 설치 및 사용법

(React Navigation 버전 : 5~, 글쓴날 : 2020.02.07)

 


* React Navigation V5 이전의 createAppContainer가 deprecated되었습니다... ㅠ.ㅠ


 

 

1. React Navigation 설치


1) React Navigation 패키지 설치

npm install @react-navigation/native

 

* npm 및 패키지 설치에 관해 궁금하시다면 ☞ [Node.js] npm 소개와 설치 및 사용법


2) 의존 패키지 설치

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view


3) iOS 설정

cd ios && pod install (이럴때는 갓 iOS입니다..)


4) Android 설정

(1) android/app/build.gradle의 dependencies 구간에 아래의 2줄 추가해주세요.

implementation 'androidx.appcompat:appcompat:1.1.0-rc01’

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02’


(2) MainActivity.java에 아래의 react-native-gesture-handler추가 코드를 삽입해주세요.

package com.reactnavigation.example;

import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;

public class MainActivity extends ReactActivity {

  @Override
  protected String getMainComponentName() {
    return "Example";
  }

  @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new ReactActivityDelegate(this, getMainComponentName()) {
      @Override
      protected ReactRootView createRootView() {
        return new RNGestureHandlerEnabledRootView(MainActivity.this);
      }
    };
  }
}


5) import 'react-native-gesture-handler';를 사용할 index.js나 app.js 맨 위에 작성

하지만 작성하지 않았는데도 이상 없이 잘 돌아감... (차후 확인할 것)


6) createStackNavigator를 사용하려면 추가로 패키지 설치

npm install @react-navigation/stack


* 기본 코드 구조 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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;

 


 

 


 

 

2. React Navigation 사용법


1) Screen 생성 및 스택화

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

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

 

선언 후

 

첫 스크린이 될 HomeScreen을 생성해주세요.

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

 

그 다음

 

createStackNavigator함수를 호출하여 사용하실 변수에 객체를 할당해주세요. (변수명 자유)

ex) const Stack = createStackNavigator();

 

그 후

 

NavigationContainer컴포넌트 안에 위에서 할당받은 객체(const Stack)의 Navigator 컴포넌트를 이용하여 각 Screen을 스택화해주세요. (4, 5, 6 라인)

1
2
3
4
5
6
7
8
9
function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

끝으로 Screen을 추가할때마다 위의 작업을 반복하면 됩니다!

 

- prop 설명 -

(1) Stack.Navigator의 initialRouteName prop : Screen이 여러 개 일시 홈 스크린을 지정합니다.

ex) <Stack.Navigator initialRouteName="Home">

 

(2) Stack.Screen의 options prop : 각 Screen의 title등을 지정할 수 있습니다.

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

 

(3) Stack.Screen의 screenOptions prop : 모든 Screen에 동일한 옵션을 지정할 수 있습니다.

ex) <Stack.Screen name="Home" component={HomeScreen} screenOptions={{ title: 'test' }} />


2) Screen간의 이동(navigation)

 

* Screen navigation 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import * as React from 'react';
import { Button, View, Text } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
 
function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate('Details')}
      />
    </View>
  );
}
 
function DetailsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Button
        title="Go to Details... again"
        onPress={() => navigation.push('Details')}
      />
      <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
      <Button title="Go back" onPress={() => navigation.goBack()} />
      <Button
        title="Go back to first screen in stack"
        onPress={() => navigation.popToTop()}
      />
    </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>
  );
}
 
export default App;

 

- navigation설명 -

(1) navigation.navigate(‘example screen’) : example screen으로 이동합니다.

단, 현재 example screen일 시 스택을 쌓을 수 없습니다. (같은 곳으로 이동 불가능)

 

(2) navigation.push('example screen') : example screen으로 이동합니다.

단, 현재 example screen이어도 중복으로 계속 스택을 쌓을 수 있습니다. (같은 곳으로 이동 가능)

 

(3) navigation.goBack() : 이전 Screen으로 이동합니다.

헤더바에 뒤로가기 버튼이 생기지만(첫 화면제외) 프로그래밍적으로 뒤로갈 때 사용합니다.

안드로이드 하단의 뒤로가기 버튼과 기능상 동일합니다.

 

(4) navigation.popToTop() : 첫 Screen으로 이동합니다. (스택에 쌓여있는 Screen이 모두 제거됩니다!)


 


 

 

여기까지 React Navigation의 설치 및 사용법이었습니다.

제가 위에서 설명해드린 사용방법들은 React Navigation의 기본적인 사용법입니다.

이 밖에도 수많은 기능들이 존재하므로 더 많은 기능과 사용법을 알고 싶으시다면...

 

* React Navigation 공식 홈페이지 : React Navigation 공식 홈페이지

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

위의 React Navigation 공식 홈페이지를 참조하시면 되겠습니다.

감사합니다!

저작자표시 비영리 변경금지 (새창열림)

'Deprecated' 카테고리의 다른 글

[Go] Go 언어 소개와 설치 및 컴파일 방법  (4) 2020.02.12
[Node.js] PM2 소개와 설치 및 사용법  (0) 2020.02.11
[Node.js] npm 소개와 설치 및 사용법  (3) 2020.02.10
[Node.js] 무료 SSL 인증서 적용 및 HTTPS 서버 구축 방법  (0) 2020.02.09
블로그 첫 시작 첫 글  (2) 2020.02.07
    'Deprecated' 카테고리의 다른 글
    • [Node.js] PM2 소개와 설치 및 사용법
    • [Node.js] npm 소개와 설치 및 사용법
    • [Node.js] 무료 SSL 인증서 적용 및 HTTPS 서버 구축 방법
    • 블로그 첫 시작 첫 글
    HelloMinchan
    HelloMinchan
    Though you should not fear failure, You should do your very best to avoid it.

    티스토리툴바