RN에는 웹브라우저처럼 history가 없기 때문에 history를 관리해주는 역할을 하는 것이 react navigation이다.
화면 전환과, 탐색 기록의 기능을 제공한다.
웹과의 차이점은 native앱에서 기대할 수 있는 제스처와 애니메이션을 제공해준다는 것이다.
Hello React Navigation
App 화면 세팅방법
// In App.js in a new projectimport*asReactfrom"react"import{View,Text}from"react-native"import{NavigationContainer}from"@react-navigation/native"import{createNativeStackNavigator}from"@react-navigation/native-stack"functionHomeScreen(){return(<Viewstyle={{flex: 1,alignItems: "center",justifyContent: "center"}}><Text>Home Screen</Text></View>)}constStack=createNativeStackNavigator()functionApp(){return(<NavigationContainer><Stack.Navigator><Stack.Screenname="Home"component={HomeScreen}/></Stack.Navigator></NavigationContainer>)}exportdefaultApp
경로지정하기 : Screen 컴포넌트를 통해서 경로를 지정할 수 있다.
Moving between screens
navigate는 너가 원하는 경로로 이동해주는 것이다. 근데 이미 그 경로에 있으면 더 이상 이동 안한다. 즉, navigate를 이용해서 현재 보고 있는 화면으로 가려고 하면 아무 일도 안 일어나는 것이다. 주로 사용자가 앱 내에서 특정 위치로 가게 할 때 이 함수를 쓰면 좋다.
한편 push는 항상 새로운 화면을 스택에 추가한다. 이미 그 경로를 방문했다 해도, push를 호출하면 지정한 경로의 새 인스턴스가 스택에 추가되는 것이다. 사용자가 앱의 동일한 경로를 여러 번 가고 싶을 때 이 함수를 사용한다.
Passing parameters to routes
navigate나 push 함수의 두 번째 인자로 객체를 넘겨줄 수 있다. 이 객체는 다음 경로로 전달된다.
중첩된 네비게이터가 있다면, 해당 중첩된 네비게이터의 경우에는 다른 방식으로 params를 전달해주어야 한다. link
Configuring the header bar
Screen 컴포넌트의 options 속성을 통해서 헤더를 커스텀할 수 있다.
<Stack.Screenname="Home"component={HomeScreen}options={{title: "My home",headerStyle: {backgroundColor: "#f4511e",},headerTintColor: "#fff",headerTitleStyle: {fontWeight: "bold",},}}/>
setOptions 메서드를 통해서도 헤더를 커스텀할 수 있다.
전체 헤더를 커스텀하고 싶다면, Stack.Navigator의 screenOptions 속성을 통해서 커스텀할 수 있다.
header에 있는 컴포넌트와 screen에 있는 컴포넌트와 상호작용하고 싶다면, setOptions을 사용하면 된다.
functionStackScreen(){return(<Stack.Navigator><Stack.Screenname="Home"component={HomeScreen}options={({ navigation, route })=>({headerTitle: props=><LogoTitle{...props}/>,headerRight: ()=><Buttontitle="Update count"/>,})}/></Stack.Navigator>)}functionHomeScreen({ navigation }){const[count,setCount]=React.useState(0)React.useEffect(()=>{// Use `setOptions` to update the button that we previously specified// Now the button includes an `onPress` handler to update the countnavigation.setOptions({headerRight: ()=>(<ButtononPress={()=>setCount(c=>c+1)}title="Update count"/>),})},[navigation])return<Text>Count: {count}</Text>}