모듈 설치
npm install @react-navigation/native @react-navigation/stack
import
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
Stack Navigation 사용하기
Stack Navigation을 사용하기 위해 Navigator()를 선언해준다.
const Stack = createStackNavigator();
Home과 Mypage 화면을 대충 만들고 import 해서 가져온 뒤
Navigation을 사용할 파일 가장 바깥쪽을 NavigationContainer로 감싸고
위에 선언해두었던 Stack을 이용하여 구현할 수 있다.
Screen 안에 들어가있는 name은 해당 화면의 별명이며 이 별명을 통해 화면을 왔다갔다 할 수 있으며
component는 import 통해 가져온 화면을 넣으면 된다.
import Home from './src/Home';
import Mypage from './src/Mypage';
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName="Home">
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Mypage" component={Mypage} />
</Stack.Navigator>
</NavigationContainer>
);
};
initialRouteName은 초기 탭을 정해주는 코드로, 생략하면 제일 위에 있는 "Home"을 처음으로 시작한다.
이제 Home.js 파일에서 버튼을 눌렀을 때 Mypage로 이동하는 것을 구현해보자.
import { useNavigation } from '@react-navigation/native';
이렇게 useNavigation을 가져온 뒤
Home 함수 안에서 아래 코드를 선언해준다. 꼭 안에 선언해줘야 한다!
const Home = () => {
const navigation=useNavigation();
//return()..
}
그리고 화면 이동하는 코드는 다음과 같다.
navigation.navigate("Mypage")
아까 위에서 말했던 Screen의 별명을 집어넣으면 그 페이지로 이동할 수 있다.
Home.js의 전체 코드를 아래와 같다.
import React from 'react';
import {View, Text, StyleSheet, TouchableOpacity} from 'react-native';
import { useNavigation } from '@react-navigation/native';
const Home = () => {
const navigation=useNavigation();
return (
<View style={styles.view}>
<TouchableOpacity onPress={()=> navigation.navigate("Mypage")}>
<Text>Go to Mypage</Text>
</TouchableOpacity>
</View>
);
};
const styles=StyleSheet.create({
view: {
backgroundColor:'#fff',
flex:1,
justifyContent:'center',
alignItems:'center'
}
})
export default Home;
실행화면
전체 코드
App.js
import React from 'react';
import {createStackNavigator} from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import Home from './src/Home';
import Mypage from './src/Mypage';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName="Home">
<Stack.Screen name="Home" component={Home} />
<Stack.Screen name="Mypage" component={Mypage} />
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
'Android > React-Native' 카테고리의 다른 글
[React-Native] Drawer Navigation (0) | 2022.10.25 |
---|---|
[React-Native] Stack과 Tab Navigation 같이 쓰기 (0) | 2022.10.22 |
[React-Native] Android / iOS에서 Icon 사용하는 법 (0) | 2022.10.18 |
[React-Native] Bottom Navigation (0) | 2022.10.17 |
[React-Native] SectionList (2) | 2022.10.15 |
댓글