ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [REACT NATIVE] 스크린에 지정한 타입에 대하여
    React Native 2023. 3. 31. 16:53

    화면 컴포넌트에 타입스크립트를 사용해서 매개변수 타입을 지정해주려고 한다.

    function HomeScreen({navigation}: HomeScreenProps) {
      const onClick = useCallback(() => {
        navigation.navigate('Details');
      }, [navigation]);
    
      return (
        <View style={{flexDirection: 'row'}}>
          <View
            style={{
              flex: 1,
              backgroundColor: 'yellow',
              alignItems: 'flex-end',
              justifyContent: 'center',
            }}>
            <Pressable
              onPress={onClick}
              style={{
                paddingVertical: 20,
                paddingHorizontal: 40,
                backgroundColor: 'blue',
              }}>
              <Text style={{color: 'white'}}>Home Screen</Text>
            </Pressable>
          </View>
          <View style={{flex: 1, backgroundColor: 'orange'}}>
            <Text>Second</Text>
          </View>
        </View>
      );
    }

     

    여기서 매개변수에 지정된 'HomeScreenProps'를 구현하려면 아래와 같은 내용을 추가해준다.

    import {
      createNativeStackNavigator,
      NativeStackScreenProps,
    } from '@react-navigation/native-stack';
    
    type RootStackParamList = {
      Home: undefined;
      Details: undefined;
    };
    
    type HomeScreenProps = NativeStackScreenProps<RootStackParamList, 'Home'>;
    type DetailsScreenProps = NativeStackScreenProps<ParamListBase, 'Details'>;

     

    정의 및 사용법

    위 코드블럭에서 기억해놔야 할 형태는 

    type HomeScreenProps = NativeStackScreenProps<RootStackParamList, 'Home'>;

    👆 이것이다.

     

    NativeStackScreenProps

    React Native Navigation (RNN) 라이브러리에서 제공하는 스크린 내비게이션의 속성을 정의한 타입이다. 이 타입을 사용하면 Native Stack Navigator에서 다음과 같은 속성을 사용할 수 있다.

    • route: 현재 스크린과 관련된 정보를 가지고 있는 객체
    • navigation: 현재 스크린과 관련된 액션을 수행할 수 있는 메소드를 가지고 있는 객체

     

     

    RootStackParamList

    스택 내비게이션에 사용되는 모든 라우트에 대한 타입을 정의한 것이다. 따라서 RootStackParamList는 다음과 같이 정의될 수 있다.

    export type RootStackParamList = {
      Home: undefined;
      Details: { id: string };
    };

    'Home'은 스크린의 이름을 나타내며, undefined는 라우트 매개변수가 필요하지 않다는 것을 의미합니다.

    'Details'는 스크린의 이름을 나타내며, { id: string }는 라우트 매개변수의 타입을 나타냅니다.

     


    NativeStackScreenProps 외에도 React Navigation에서는 다른 내비게이션 타입에 대한 속성을 정의한 타입을 제공한다.

    예를 들어, BottomTabScreenProps는 하단 탭 내비게이션의 속성을 정의하고 있으며, DrawerScreenProps는 드로어 내비게이션의 속성을 정의하고 있습니다. 필요 시 찾아보자.

Designed by Tistory.