TIL: RN, TS | ReactNavigation Type checking (3) Nesting Navigators - 220914

Lumpen·2022년 9월 14일
0

ReactNavigation

목록 보기
3/14

Nesting Navigators

중첩된 네비게이터 내의 화면과 params에 대한 type checking

중첩된 화면에서 화면과 params 프로퍼티를 전달하면서 중첩된 네비게이터의 화면으로 이동할 수 있다

navigation.navigate('Home', {
  screen: 'Feed',
  params: { sort: 'latest' },
});

이 type을 검사하려면 중첩된 네비게이터가 포함된 화면에서 params를 추출해야 한다
이 작업은 NavigatorScreenParams 유틸리티를 사용하여 할 수 있다

import { NavigatorScreenParams } from '@react-nacigation/native'

type TabParamList = {
  Home: NavigatorScreenParams<StackParamList>;
  Profile: { userId: string };
};

navigator를 중첩할 때 화면의 navigation prop은 여러 개 navigation prop의 조합이다
만약 stack 내부에 Tab이 있다면 navigation prop은 jumpTo와 push 모두 가지고 있게 될 것이다
multiple navigators의 types를 쉽게 결합해주는
CompositeScreenProps type을 사용할 수 있다

import type { CompositeScreenProps } from '@react-navigation/native';
import type { BottomTabScreenProps } from '@react-navigation/bottom-tabs';
import type { StackScreenProps } from '@react-navigation/stack';

type ProfileScreenProps = CompositeScreenProps<
  BottomTabScreenProps<TabParamList, 'Profile'>,
  StackScreenProps<StackParamList>
>;

CompositeScreenProps 유형은 두가지 매개변수(parameters)를 사용한다
첫 번째 매개변수는 기본 navigation props의 type으로 현재 화면을 소유한 navigation에 대한 type이다 ('Profile' 화면을 포함하는 tab navigator의 type)
두 번째 매개변수는 보조 navigation props의 type으로 부모 navigation에 대한 유형이다

여러 부모를 navigator의 경우 두 번째 매개변수에 CompositeScreenProps로 중첩된 navigation props type을 전달할 수 있다

type ProfileScreenProps = CompositeScreenProps<
  BottomTabScreenProps<TabParamList, 'Profile'>,
  CompositeScreenProps<
    StackScreenProps<StackParamList>,
    DrawerScreenProps<DrawerParamList>
  >
>;

Annotating useNavigation

useNavigation에서 얻은 navigation prop에 annotate하기 위해 다음과 같은 type parameter를 사용할 수 있다

const navigation = useNavigation<ProfileScreenNavigationProp>();

사용하는 type parameter가 올바르지 않을 수 있고 정적으로 확인할 수 없기 때문에 완전히 안전한 type은 아니다

Annotation useRoute

const route = useRoute<ProfileScreenRouteProp>();

useNavigation과 마찬가지로 사용하는 type parameter가 올바르지 않을 수 있고 정적으로 확인할 수 없기 때문에 완전히 안전한 type은 아니다

profile
떠돌이 생활을 하는. 실업자는 아니지만, 부랑 생활을 하는

0개의 댓글