REACT NATIVE

[REACT NATIVE] 리액트 내비게이션 라이브러리 - 네이티브 스택 내비게이터

예글 2022. 11. 1. 16:31

- 리액트 내비게이션 라이브러리에는 다른 상황에 사용할 수 있는 다양한 내비게이터가 있음

- 네이티브 스택 내비게이터가 가장 흔히 사용됨 

- 안드로이드: Fragment

- iOS: UINavigationController

- 라이브러리를 추가로 설치해주어야 함

 yarn add @react-navigation/native-stack

 

1.  screens 디렉터리

- 화면 전용 컴포넌트 저장

 

2. 네이티브 스택 내비게이터 만들기

- createNativeStackNavigator 함수 사용

- 위 함수 사용하면 Stack이라는 객체 만들어짐

- Stack 안에 Stack.Navigator 컴포넌트, Stack.Screen 컴포넌트 들어있음

- Stack.Navigator : NabigationContainer 사이에 넣어야 정상적으로 작동함

- Stack.Screen : 각 화면 설정

  • name: 화면의 이름을 설정하는 Props / 다른 화면으로 이동하거나 현재 화면이 어떤 화면인지 조회할 때 사용
  • initialRouteName : 네이티브 스택 내비게이터에서 기본적으로 보여줄 화면의 이름(초기 화면) 
import DetailScreen from './screens/DetailScreen';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

const Stack = createNativeStackNavigator();

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

export default App;

3. 스크린 이동하기

- 스크린으로 사용된 컴포넌트(HomeScreen, DetailScreen): navigation이라는 객체를 Props로 받아올 수 있음

- navigation/push를 사용해 다른 화면으로 이동할 수 있음

import React from 'react';
import {View, Button} from 'react-native';

function HomeScreen({navigation}) {
  return (
    <View>
      <Button
        title="Detail 열기"
        onPress={() => navigation.navigate('Detail')} //Detail 화면으로 이동
      />
    </View>
  );
}

export default HomeScreen;

- navigation.navigate('Detail') == navigation.push('Detail')

 

4. 라우트 파라미터

- 새로운 화면을 보여줄 때 의존해야 하는 어떤 값이 있으면 라우트 파라미터 설정

- 객체 타입

- 라우트 파라미터를 설정해 화면을 전환할 때는 navigate 또는 push 함수의 두 번째 인자로 객체를 설정

 ex) navigation.navigate('Detail',{ id : 1 }) 

        navigation.push('Detail',{ id : 2 })

- 스크린으로 사용된 컴포넌트: route라는 Props 받아옴 -- 객체타입 

( 다음과 같은 정보가 들어있음)

 

  { "key" : .........,       // 고유 ID - 새로운 화면이 나타날 때 자동으로 생성

    "name" : "Detail",  // 화면 이름 - App 컴포넌트에서 네이티브 스택 내비게이터를 설정할 때 지정한 이름

     "params" : {"id" : 1}   // 화면 전환 시 지정한 라우트 파라미터

   }

 

- navigate vs push

  • navigate : 새로 이동할 화면이 현재 화면과 같으면 새로운 화면을 쌓지 않고 파라미터만 변경 / 다른 내비게이터에도 있음
  • push: 새로운 화면이 스택에 쌓여가면서 화면이 전환 / 네이티브 스택 내비게이터에서만 사용 가능

 

5. 뒤로가기

navigation.pop()

navigation.popToTop() : 가장 첫 번째 화면으로 이동

 

6. 헤더 커스터마이징

<타이틀 텍스트, 스타일 변경>

1. Stack.Screen의 Props로 설정

<Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{
            title: '홈',
            headerStyle: {backgroundColor: '#9292D8'},
            headerTitleStyle: {fontWeight: 'bold', fontSize: 20},
          }}
        />

2. navigation.setOptions 함수 사용

useEffect(() => {
    navigation.setOptions(
      {
        title: `상세 정보 - ${route.params.id}`,
      },
      [navigation, route.params.id],
    );
  });

- 컴포넌트가 처음 화면에 나타난 다음에 navigation.setOptions 함수를 호출해 타이틀 텍스트 변경

 

<헤더 좌측, 타이틀, 우측 영역에 다른 컴포넌트 보여주기>

<Stack.Screen
          name="Detail"
          component={DetailScreen}
          options={{
            headerLeft: ({onPress}) => (
              <TouchableOpacity onPress={onPress}>
                <Text>Left</Text>
              </TouchableOpacity>
            ),
            headerTitle: ({children}) => (
              <View>
                <Text>{children}</Text>
              </View>
            ),
            headerRight: () => (
              <View>
                <Text>Right</Text>
              </View>
            ),
          }}
        />

- 안드로이드 좌측 화살표 아이콘 제거하려면 --> headerBackVisible : false

 

'REACT NATIVE' 카테고리의 다른 글

[REACT NATIVE] StyleSheet  (0) 2022.10.31
[REACT NATIVE] Props, defaultProps  (0) 2022.10.31
[REACT NATIVE] 설치와 파일 생성  (0) 2022.10.31