헤더 만들기
(1)
라이브러리 설치 필요
1) yarn add @react-navigation/native
2) yarn add react-native-screens react-native-safe-area-context
+
3) 네이티브 스택 내비게이터
Yarn add @react-navigation/native-stack
- 안드로이드의 fragments, ios에서의 UINavigationController를 사용해 일반 네이티브 앱과 정확히 동일한 방식으로 화면을 관리한다.
- 사용법: (App.tsx)
import {createNativeStackNavigator} from '@react-navigation/native-stack';
const Stack = createNativeStackNavigator();
// Stack 이라는 객체가 만들어짐
//이 안에 Stack.Navigator 컴포넌트와 Stack.screen 컴포넌트가 존재
// 이거는 NavigationContainer 사이에 넣어야 정상적으로 작동
// Stack.Screen 컴포넌트 사용하여 각 화면을 설정할 수 있음
//이 화면에 설정된 name은 화면 이름을 설정하는 props
// 이 값은 다른 화면으로 이동하거나 현재 화면이 어떤 화면인지 조회 할 때 사용
(2) 스크린 이동 - 버튼 눌렀을 때 다른 화면으로 이동하는 법
# HomeScreen.js(홈화면)
import React from 'react';
import {View,Button} from 'react-native';
function HomeScreen({navigation}){ // 스크린으로 사용된 컴포넌트는 navigation이라는 객체를 props으로 받아올 수 있음
return(
<View>
<Button title="detail 1"
onPress ={()=> navigation.push('Detail',{id:1})}
/>
<Button title="detail 2"
onPress ={()=> navigation.push('Detail',{id:2})}
/>
<Button title="detail 3"
onPress ={()=> navigation.push('Detail',{id:3})}
/>
</View>
);
}
export default HomeScreen;
//push함수와 navigate함수의 차이 (navigation.push vs navigation.navigate )
//push : 스택에 쌓여가면서 화면 전환 . 뒤로가기 버튼 누르면 이전 화면 열림. 네이티브 스택 네비게이터에서만 사용 가능
//navigate : 새로 이동할 화면이 현재 화면과 같으면 새로운 화면을 쌓지 않고 파라미터만 변경. 뒤로가기 버튼 한번이면 바로 홈 화면
# DetailScreen.js(새부 페이지)
import React from 'react';
import {View,Text} from 'react-native';
//route : 객체 타입
객체 타입 :
{"key" : " "
"name" : ' "
"params" : " "
}
//key,name,params으로 이루어짐
//key : 화면의 고유 id로 새로운 화면이 나타날 때 자동생성
//name : 화면의 이름,app 컴포넌트에서 네이티브 스택 내비게이터를 설정할 때 지정한 이름
//params : 우리가 화면 전환시 지정한 라우트 파라미터 {"id :1"}
function DetailScreen(route){
return (
<View style = {styles.block}>
<Text style = {sytles.text}>id: {route.params.id}
</Text>
<View style={styles.buttons}>
<Button
title = "다음"
onPress={()=> navigation.push('Deatail',{id:route.params.id +1})}/>
<Button title = "뒤로가기" onPress={()=> navigation.pop()}/>
<Button title = "처음으로" onPress={()=> navigation.popToTop()}/>
</View>
</View>
);
}
const styles = StyleSheet.create({
block:{
flex:1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize:48,
},
buttons:{
flexDirection:'row',//여러버튼이 한 줄에 나타날 수 있도록
},
});
export default DetailScreen;
(3) 타이틀 텍스트 변경 (헤더 커스터마이징)
방법 1. Stack.Screen의 props로 설정하는 것
(App.js)
function App(){
return(
<NavigationContainer>
<Stack.Navigator initialRouteName = "Home">
<Stack.Screen name = "Home" component = { HomeScreen}
options={{
title:'홈',}}/>
<Stack.Screen name = "Detail" component = { DetailScreen}/>
</Stack.Navigator>
</NavigationContainer>
)
}
- 라우터 파라미터 참조하는 경우(detail.js)
App.js
<Stack.Screen name = "Detail" component = { DetailScreen}
options = {({route}) =>({
title : `상세정보 - ${route.params.id}`,
})}/>
방법 2. 화면 컴포넌트에서 navigation.setOptions 함수 사용
(HomeScreen.js)
function HomeScreen({navigation}){
useEffect(()=>{
navigation.setOptions({title:'홈'});
},[navigation]);
//useEffect: Hook으로 특정 값이 바뀔 때 또는 컴포넌트가 화면에 나타날 때 우리가 원하는 작업을 할 수 있음
- 라우터 파라미터 참조하는 경우(detail.js)
DetailScreen.js
function DetailScreen(route,navigation){
useEffect(()=>{
navigation.setOptionsd({
title:`상세정보 - ${route.params.id}`,
});
}, [navigation,route.params.id]);
(4) 헤더 좌측, 타이틀, 우측 영역에 다른 컴포넌트 보여주기
<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>
),
.................................................................................................................................................................................................전체코드
App.tsx
DetailScreen.js
HomeScreen.js