React Native에서 네비게이션은 계층적으로 구성됩니다:
npm install @react-navigation/native @react-navigation/stack @react-navigation/bottom-tabs
// types/navigation.ts
export type ProfileStackParamList = {
ProfileMain: undefined;
EditProfile: {
userId: string;
onUpdate?: () => void;
};
Settings: undefined;
};
export type HomeStackParamList = {
Feed: undefined;
PostDetail: { postId: string };
Comments: { postId: string };
};
import { createStackNavigator } from '@react-navigation/stack';
const ProfileStack = createStackNavigator<ProfileStackParamList>();
const ProfileStackNavigator = () => {
return (
<ProfileStack.Navigator>
<ProfileStack.Screen
name="ProfileMain"
component={ProfileScreen}
options={{ headerShown: false }}
/>
<ProfileStack.Screen
name="EditProfile"
component={EditProfileScreen}
/>
<ProfileStack.Screen
name="Settings"
component={SettingsScreen}
/>
</ProfileStack.Navigator>
);
};
const Tab = createBottomTabNavigator();
export const MainTabNavigator = () => {
return (
<Tab.Navigator>
<Tab.Screen
name="Home"
component={HomeStackNavigator}
options={{
tabBarIcon: ({ color }) => (
<HomeIcon color={color} />
),
}}
/>
<Tab.Screen
name="Search"
component={SearchStackNavigator}
options={{
tabBarIcon: ({ color }) => (
<SearchIcon color={color} />
),
}}
/>
<Tab.Screen
name="Profile"
component={ProfileStackNavigator}
options={{
tabBarIcon: ({ color }) => (
<UserIcon color={color} />
),
}}
/>
</Tab.Navigator>
);
};
// 방법 1: navigation prop 사용
type ProfileScreenProps = {
navigation: StackNavigationProp<ProfileStackParamList, 'ProfileMain'>;
};
const ProfileScreen = ({ navigation }: ProfileScreenProps) => {
return (
<View>
<TouchableOpacity
onPress={() => navigation.navigate('EditProfile', {
userId: '123',
onUpdate: () => console.log('Profile updated')
})}
>
<Text>프로필 수정</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => navigation.navigate('Settings')}
>
<Text>설정</Text>
</TouchableOpacity>
</View>
);
};
// 방법 2: useNavigation 훅 사용
import { useNavigation } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
const PostCard = () => {
const navigation = useNavigation<StackNavigationProp<HomeStackParamList, 'Feed'>>();
return (
<TouchableOpacity
onPress={() => navigation.navigate('PostDetail', {
postId: '456'
})}
>
<Text>게시글 상세보기</Text>
</TouchableOpacity>
);
};
import { StackNavigationProp } from '@react-navigation/stack';
type ProfileScreenNavigationProp = StackNavigationProp
<ProfileStackParamList>,
'ProfileMain'
>;
const ProfileScreen = ({ navigation }: { navigation: ProfileScreenNavigationProp }) => {
// 타입 안전한 네비게이션 사용 가능
};
이렇게 네비게이션을 설정하면 앱 내에서 자연스러운 화면 전환이 가능해집니다.
특히 타입스크립트를 사용할 때는 타입 정의를 꼭 해주어야 안전한 네비게이션이 가능합니다!