React-Native "NativeStackScreenProps"를 활용하여 타입 체크하기

nevermind·2023년 2월 26일
0

React-Native

목록 보기
5/8

https://reactnavigation.org/docs/typescript/

import type { NativeStackScreenProps } from '@react-navigation/native-stack';

type RootStackParamList = {
  Home: undefined;
  Profile: { userId: string };
  Feed: { sort: 'latest' | 'top' } | undefined;
};

type Props = NativeStackScreenProps<RootStackParamList, 'Profile'>;
  • 왜 NativeStackScreenProps로 한번 더 감싸는지에 대한 의문이 생겼다
  • 공식문서를 살펴보니

To type check our screens, we need to annotate the navigation prop and the route prop received by a screen. The navigator packages in React Navigation export a generic types to define types for both the navigation and route props from the corresponding navigator.

우리의 화면들의 타입을 체크할 때, 각 화면마다 정보들(navigation prop, route prop)이 필요하다. navigator packages는 navigator와 일치하는 navigation prop & route prop에 타입을 정의하기 위한 제네릭 타입을 내보낸다

The type takes 3 generics:
1. The param list object we defined earlier
2. The name of the route the screen belongs to
3. The ID of the navigator (optional)
If you have an id prop for your navigator, you can do:

  1. 앞에서 정의한 매개변수 목록 객체
  2. 화면이 속한 경로의 이름
  3. 네비게이터의 ID(선택 사항)
    id네비게이터에 대한 내용이 있는 경우 아래와 같이 할 수 있다.

type Props = NativeStackScreenProps<RootStackParamList, 'Profile', 'MyStack'>;


즉 , NativeStackScreenProps는 react-navigation에서 사용하는 타입들을 연결해주는 것으로 보면 될 것같다.

import { NativeStackScreenProps } from "@react-navigation/native-stack";
import React, { useCallback, useRef, useState } from "react";
import { RootStackParamList } from "../../App";


type SignInScreenProps = NativeStackScreenProps<RootStackParamList, "SignIn">;
export default function SignIn({ navigation }: SignInScreenProps) {
	...
	const toSignup = useCallback(() => {
		navigation.navigate("SignUp");
	}, []);

위와 같이 props로 받는다면 navigation.navigate("SignUp")이렇게 쓸 수 있고

import { useNavigation } from "@react-navigation/native";

export default function SignIn() {
	const navigation = useNavigation();
  	const toSignup = useCallback(() => {
		navigation.navigate("SignUp");
	}, []);
}

아니면 useNavigation()을 호출해서 할 수도 있다.

profile
winwin

0개의 댓글