개발/리액트네이티브
RN navigation
z-zero
2022. 11. 18. 18:00
공식문서
https://reactnavigation.org/docs/getting-started/
https://reactnavigation.org/docs/getting-started/
reactnavigation.org
expo로 프로젝트 생성 후 tabs로 설치하면 자동으로 설치된다. 그렇지 않으면 하나하나 설치해주어야 한다. 필자는 처음부터 expo로 설치했다.
설치
npm install @react-navigation/native
npm install @react-navigation/native-stack
with expo
npx expo install react-native-screens react-native-safe-area-context
with bare React Native
npm install react-native-screens react-native-safe-area-context
typescript를 사용하면 index.tsx에 네비게이션 목록을 넣어주어야 한다.
이 역시 expo로 초기설치 하면 기본적인 것이 나와 있어 응용하면 된다.
사용법
// types/index.tsx
export type CommunityStackList = {
CommunityMain: undefined;
CommunityDetail: undefined;
};
export type CommunityStackScreenProps<Screen extends keyof CommunityStackList> =
NativeStackScreenProps<CommunityStackList, Screen>;
Stack.Navigator에는 screenOptions, Stack.screen에는 options로 헤더를 설정할 수 있다.
BottomTab
하단 탭 네비게이터가 메인으로 되어있고 이에 따라 중첩 네비게이트가 가능하다.
screenOptions={{
tabBarActiveTintColor: "red",
}}
tabBarActiveTintColor로 색상을 변경할 수 있다. 자세한 건 상단 문서에 잘 나와있다.
중첩 네이게이션
//navigations/index.tsx
const CommunityStack = createNativeStackNavigator<CommunityStackList>();
function CommunityStackScreen() {
return (
<CommunityStack.Navigator
screenOptions={{
headerShown: false,
}}
>
<CommunityStack.Screen name="CommunityMain" component={CommunityScreen} />
<CommunityStack.Screen
name="CommunityDetail"
component={CommunityDetailScreen}
/>
</CommunityStack.Navigator>
);
};
const BottomTab = createBottomTabNavigator<RootTabParamList>();
function BottomTabNavigator() {
return (
<BottomTab.Navigator
initialRouteName="Main"
screenOptions={{
tabBarActiveTintColor: "red", // 상단 설명 부분
}}
>
<BottomTab.Screen
name="Main"
component={MainScreen} // 이 부분은 screens디렉토리의 MainScreen
options={{
headerShown: false,
tabBarIcon: ({ color }) => <TabBarIcon name="home" color={color} />,
}}
/>
<BottomTab.Screen
name="Community"
component={CommunityStackScreen} // 코드 상단 CommunityStackScreen을 컴포넌트로 가진다.
options={{
headerShown: false,
tabBarIcon: ({ color }) => (
<TabBarIcon name="account-group" color={color} />
),
}}
/>
</BottomTab.Navigator>
);
}
function TabBarIcon(props: { //하단에 아이콘
//MaterialCommunityIcons를 사용하려면 코드 최상단에 import { MaterialCommunityIcons } from "@expo/vector-icons"; 추가한다
name: React.ComponentProps<typeof MaterialCommunityIcons>["name"];
color: string;
}) {
return (
<MaterialCommunityIcons size={30} style={{ marginBottom: -3 }} {...props} />
);
}
이런식으로 중첩 네비게이트가 가능하다.
코드 내 사용
screens디렉토리의 파일인 경우 이미 navigation/index.tsx에 컴포넌트로 들어가있기 때문에 props로 navigation을 받는다. 하지만 컴포넌트 디렉토리의 파일인 경우 useNavigatoin을 사용해야 한다.
import { useNavigation } from "@react-navigation/native"; //컴포넌트일 경우만 추가
const navigation = useNavigation(); //컴포넌트일 경우만 추가
navigation.replace("Login"); // 이런식으로 사용