반응형

모바일에서도 페이지별로 구성되어 페이지를 이동하는 형태를 많이 사용되는데,Reactreact-router-dom처럼 페이지를 이동하는 방법을 알아보겠습니다.

🟢 React-Native Navigation 설정하기

📦 패키지 설치

먼저 프로젝트에 해당 패키지를 설치합니다

npm install @react-navigation/native @react-navigation/native-stack

설치가 완료되면 다음 종속성을 설치합니다(expo버전이 아닙니다)

npm install react-native-screens react-native-safe-area-context

여기까지 설치가 끝나면 ios에 pod를 설치를 진행합니다

cd ios
pod install
cd ..

여기까지 설치가 끝났으면 프로젝트를 재시작하면 좋습니다

🚀 프로젝트 구성하기

App.tsx

import React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import HomePage from './src/pages/HomePage.tsx';
import ProfilePage from './src/pages/ProfilePage.tsx';

const Stack = createNativeStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Home"
          component={HomePage}
          options={{title: 'Welcome'}}
        />
        <Stack.Screen name="Profile" component={ProfilePage} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

/src/pages/HomePage.tsx

import {Button, Text, View} from 'react-native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';

interface HomePageProps {
  navigation: NativeStackNavigationProp<any, 'Home'>;
}

const HomePage = ({navigation}: HomePageProps) => {
  const linkProfile = () => {
    navigation.navigate('Profile', {name: 'Jane'});
  };
  return (
    <View>
      <Text>Home Page!!!</Text>
      <Button title="Profile 이동" onPress={linkProfile} />
    </View>
  );
};

export default HomePage;

/src/pages/ProfilePage.tsx

import {Button, Text, View} from 'react-native';
import {NativeStackNavigationProp} from '@react-navigation/native-stack';

interface ProfilePageProps {
  navigation: NativeStackNavigationProp<any, 'Home'>;
  route: any;
}
const ProfilePage = ({navigation, route}: ProfilePageProps) => {
  const linkHome = () => {
    navigation.navigate('Home', {title: '제목들어갈자리'});
  };
  return (
    <View>
      <Text>Profile Page</Text>
      <Text>{route?.param?.name} Profile </Text>
      <Button title="Home 이동" onPress={linkHome} />
    </View>
  );
};

export default ProfilePage;

결과

이동

코드구조

반응형