-
[ React Native ] Stack NavigationApplication/React Native 2025. 10. 8. 18:49반응형
이전에 bottom tabs을 했다가 bottom tabs을 빼고 진행하기로 결정.
이후 버튼을 누르면 페이지 이동이 필요하여 stack navigation을 사용
Initialized
native-stack 패키지를 설치
npm install react-native-screens @react-navigation/native-stack
Stack Navigation
사용방법은 이전 bottom-tabs와 비슷했다.
각 페이지별로 option에 애니메이션 진행 방향을 설정해서 뒤로가기나 이동이 자연스럽게 이루어지도록 설정
첫 페이지는 home 페이지로 설정
App.tsx자체에서 만들어도 되지만,
App.tsx에는 나중에 provider나 이것저것 추가하게 되면 지저분해보일까봐 navigation을 따로 만들었다.
import {NavigationContainer} from "@react-navigation/native"; import { createNativeStackNavigator, } from '@react-navigation/native-stack'; import {HomeScreen, SettingScreen} from "@/screens"; const Stack = createNativeStackNavigator(); const StackNavigation = () => { return ( <NavigationContainer> <Stack.Navigator initialRouteName="Home" screenOptions={{ headerShown: false, // 필요하면 헤더 숨김 }} > {/*메인 */} <Stack.Screen name="Home" component={HomeScreen} options={{ animation: 'slide_from_left', }} /> {/* 설정 */} <Stack.Screen name="Setting" component={SettingScreen} options={{ animation: 'slide_from_right', }} /> </Stack.Navigator> </NavigationContainer> ) } export default StackNavigation
이후 App.tsx파일에서
만든 StackNavigation 컴포넌트를 추가해준다.
<SafeAreaProvider> <StackNavigation/> </SafeAreaProvider>
Useage
header 컴포넌트를 만들어서 이 컴포넌트에서 설정 버튼과 뒤로가기 버튼을 추가
더보기FitView와 BetweenView는 직접만든 컴포넌트로
fitView는 안의 내용의 높이가 자식의 크기에 맞춰서 적용되게 했고,
BetweenView는 단순히 양끝에 붙히게 해주는 컴포넌트이다. 스타일을 계속 주기 귀찮아서 그냥 컴포넌트로 만들었다.
페이지이동의 경우에는 navigation.navigate("이동할 페이지 이름")
StackNavigation을 만들때 설정한 name을 넣어주면 된다.
타입스크립트를 쓰다보니 navigate에서 타입에러가 나기에 타입을 추가했다.
아직 해보지는 않았지만, 아마도 각 화면 전환시마다 서로 parameter를 전달하여 사용할 수 있을 것 같은데 아직은 전달할게 없기때문에 undefined로 설정
export type RootStackParamList = { Home: undefined; Setting: undefined; };
type NavigationProp = NativeStackNavigationProp<RootStackParamList>; const AppHeader = (props: Props) => { const navigation = useNavigation<NavigationProp>(); const onPressBack = () => { navigation.navigate("Home") } return ( <FitView style={styles.container}> { props.type ?? true ? <BetweenView> <AppText>Title</AppText> <SvgIcon name="Setting" onPress={() => navigation.navigate("Setting")} /> </BetweenView> : <BetweenView> <SvgIcon name="ArrowLeft" onPress={onPressBack} /> </BetweenView> } </FitView> ) }
그럼 header에서 설정 버튼을 누르면 설정으로 이동하고 설정에서 뒤로가기버튼을 누르면 다시 home으로 이동된다.
728x90반응형'Application > React Native' 카테고리의 다른 글
[ React Native ] i18n 적용 언어변경하기 (0) 2025.10.12 [ React Native ] 직접 Popup 만들기 (0) 2025.10.08 [ React Native ] AsyncStorage key 값 저장 (0) 2025.10.06 [ React Native ] 다크모드 테마설정 간단하게 처리하기 (0) 2025.10.06 [ React Native ] react-navigation bottom-tabs (0) 2025.10.05