Develop/React Native

[React Native] react-navigation ***v5*** 사용법

안다희 2020. 2. 17. 19:38
728x90

[참고링크]

https://yuddomack.tistory.com/entry/React-Navigation%EC%9C%BC%EB%A1%9C-%EB%A1%9C%EA%B7%B8%EC%9D%B8-%ED%83%AD-%EB%84%A4%EB%B9%84%EA%B2%8C%EC%9D%B4%ED%84%B0-%ED%99%94%EB%A9%B4-%EA%B5%AC%EC%84%B1%ED%95%98%EA%B8%B0

 

React Navigation으로 로그인, 탭 네비게이터 화면 구성하기

이전에 react-native-navigation 사용법을 포스팅 한 적이 있는데, react-navigation이 react-native-navigation보다 설치도 간편하고, 사용하기 편리하고, 무엇보다 성능이 좋아져서 최근에 자주 사용하고 있습..

yuddomack.tistory.com

이건 react-navigation v4....

 

[문서] new v5!!!!

https://reactnavigation.org/docs/en/getting-started.html

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

v5의 문서를 그대로 따라하면 됨! (문서가 아주 잘되어있다.)

 

1.

npm install @react-navigation/native

 

2. 

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

 

3. 

cd ios; pod install; cd ..

 

4. index.js 맨위에 추가 (이 코드 위에 어떠한 코드도 있어선 안됨)

import 'react-native-gesture-handler';

 

5. NavigationContainer로 감싸주기

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

export default function App() {
  return (
    <NavigationContainer>
      {/* Rest of your app code */}
    </NavigationContainer>
  );
}

 

6. 

npm install @react-navigation/stack

 

7. Stack, Stack.Navigator, Stack.Screen 추가, navigate

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

function HomeScreen({ navigation }) {
  return (
    <TouchableOpacity onPress={() => navigation.navigate('Detail')} style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Detail Screen</Text>
    </TouchableOpacity>
  );
}

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

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{ title: '홈화면 타이틀!!' }}
          initialParams={{ itemId: 42 }}
        />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

options, initialParams={{ itemId: 42 }} 참고~

 

여기서 잠깐! Detail에서 또다시 Detail로 가고싶으면 navigate가 안먹힘. 이 때는 push를 사용하자!

뒤로가기: 원래제공하지만, 쓰고싶다면

navigation.goBack()

 

뒤로 가는 동시에 뒤로 가는 화면을 첫 스택에 넣고 싶다면

navigation.popToTop()

 

 

8. pass params

// App에서 navigation.navigate('Detail', { count: 1 })로 넘겼다고 가정

const Detail = ({route, navigation}) => {
  const {count} = route.params;
  return (
    <>
      <TouchableOpacity
        onPress={() => navigation.popToTop('Home')}
        style={{backgroundColor: 'yellow', flex: 1}}>
        <Text>Back</Text>
      </TouchableOpacity>
      <TouchableOpacity
        onPress={() => navigation.push('Detail', {count: count + 1})}
        style={{backgroundColor: 'blue', flex: 1}}>
        <Text>Detail {count}</Text>
      </TouchableOpacity>
    </>
  );
};

 

9. createNativeStackNavigator

별로 다른게 없는거 같은데.. 뭐지? 잘 이해를 못했음

https://reactnavigation.org/docs/en/native-stack-navigator.html

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

 

10. drawer

@types/react-navigation 없어짐.

https://reactnavigation.org/docs/en/drawer-based-navigation.html

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

문서 잘 따라가삼! 문서가 잘 되어있네.

 

11. v4와 달라진 점

https://reactnavigation.org/docs/en/upgrading-from-4.x.html

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

https://reactnavigation.org/docs/en/nesting-navigators.html

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

이전에는 StackNavigator와 DrawerNavigator 를 createXNavigator 안에 옵션으로 줬는데, 확 달라짐.

 

index.js

/**
 * @format
 */

import 'react-native-gesture-handler'; // TODO: production에서 에러 날 가능성이 있음

import App from './App';
import {AppRegistry} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import Notice from './src/components/Notice';
import React from 'react';
import Setting from './src/components/Setting';
import Sub from './src/components/Sub';
import {name as appName} from './app.json';
import {createDrawerNavigator} from '@react-navigation/drawer';
import {createStackNavigator} from '@react-navigation/stack';
// import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {enableScreens} from 'react-native-screens';

enableScreens();

const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();

const Root = () => (
  <Stack.Navigator initialRouteName="Home">
    <Stack.Screen name="Home" component={App} />
    <Stack.Screen name="Sub" component={Sub} />
  </Stack.Navigator>
);

const Side = () => (
  <Stack.Navigator initialRouteName="Notice">
    <Stack.Screen name="Notice" component={Notice} />
    <Stack.Screen name="Setting" component={Setting} />
  </Stack.Navigator>
);

const Container = () => (
  <NavigationContainer>
    <Drawer.Navigator initialRouteName="Root">
      <Drawer.Screen name="Root" component={Root} />
      <Drawer.Screen name="Side" component={Side} />
    </Drawer.Navigator>
  </NavigationContainer>
);

AppRegistry.registerComponent(appName, () => Container);

 

 

Root와 Side를 주목!

Container 안에는 Drawer가 있다. 그 안에는 Root, Side가 있는데 이 2개가 사이드바를 형성한다. Root가 default이고.

Root, Side 안 각각의 스크린은은 Stack.Screen으로 감싸줘서 화면 간 전환이 자연스럽다.

initialRouteName 이전으로 goBack하면 화면전환 끊기겠지. 아무튼 이걸 생각해서 자연스럽게 화면 구성하기!

 

Stack.Navigator 안에 들어가지 않은 스크린은 화면 전환이 뚝뚝 끊긴다.

 

drawer와 stack을 합치고 싶었는데 해결했다 ㅎㅎ

 

 

keyword: drawer-inside-stack-navigation-in-react-native

 

12. 여기까지 커밋 완료

 

https://github.com/daheeahn/practiceNavigation/commit/b9f4fd3e933337f28cb396c2dcba2bd6135052a1

 

react-navigation v5: StackNavigator, DrawerNavigator · daheeahn/practiceNavigation@b9f4fd3

Permalink Browse files react-navigation v5: StackNavigator, DrawerNavigator Loading branch information Showing 66 changed files with 21,206 additions and 0 deletions. +6 −0 .buckconfig +4 −0 .eslintrc.js +75 −0 .flowconfig +1 −0 .gitattributes +59 −0 .giti

github.com

 

첫번째 커밋 완료

 

13. TabNavigator

https://reactnavigation.org/docs/en/tab-based-navigation.html

 

React Navigation · Routing and navigation for your React Native apps

Routing and navigation for your React Native apps

reactnavigation.org

 

위에랑 똑같다.

 

 

import 'react-native-gesture-handler'; // TODO: production에서 에러 날 가능성이 있음

import App from './App';
import {AppRegistry} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import React from 'react';

import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';

const Tab = createBottomTabNavigator();

const Container = () => (
  <NavigationContainer>
    <Tab.Navigator>
      <Tab.Screen name="Home" component={App} />
      <Tab.Screen name="Sub" component={Sub} />
    </Tab.Navigator>
  </NavigationContainer>
);

AppRegistry.registerComponent(appName, () => Container);

 

 

14. setParams

The setParams method lets us update the params (route.params) of the current screen. setParams works like React's setState - it merges the provided params object with the current params.

function ProfileScreen({ navigation: { setParams } }) {
  render() {
    return (
      <Button
        onPress={() =>
          navigation.setParams({
            friends:
              route.params.friends[0] === 'Brent'
                ? ['Wojciech', 'Szymon', 'Jakub']
                : ['Brent', 'Satya', 'Michaś'],
            title:
              route.params.title === "Brent's Profile"
                ? "Lucy's Profile"
                : "Brent's Profile",
          })
        }
        title="Swap title and friends"
      />
    );
  }
}

setState처럼 작동!

 

 

15. 타입스크립트 타입체킹

https://coding-dahee.tistory.com/157

 

[React Native] react-navigation **v5** type checking with typescript / 타입스크립트 타입체킹

 

coding-dahee.tistory.com

 

 

 

 

 

 

 

 

 

 

 

 

[보일러플레이트! 만들어보기]

The setParams method lets us update the params (route.params) of the current screen. setParams works like React's setState - it merges the provided params object with the current params.

 
 
 
 
출처: https://mingos-habitat.tistory.com/34 [밍고의서식지:티스토리]