ㅇㅇㅈ Blog

프론트엔드 수행중

0%

react-native-navigate type error

NativeStackScreenProps와 NativeStackNavigationProp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export type ProfileButtonListType = {
iconName: string
buttonTxt: string
rightIcon: string
iconColor: keyof Colors
path?: keyof ProfileStackParamList
}
const profileButtonList: ProfileButtonListType[] = [
{ iconName: 'form', iconColor: 'success', buttonTxt: '나의 소모임', rightIcon: 'right', path: 'MyGroupScreen' },
{ iconName: 'user', iconColor: 'primary', buttonTxt: '프로필 수정', rightIcon: 'right', path: 'EditProfileScreen' },
{ iconName: 'logout', iconColor: 'warning', buttonTxt: '로그 아웃', rightIcon: 'right' },
]

{profileButtonList.map(button => (
<ProfileButton key={button.buttonTxt} buttonProps={button} />
))}

path를 props로 넘겨서 navigate한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
interface ProfileButtonProps {
buttonProps: ProfileButtonListType
}

type ProfieScreenProp = NativeStackScreenProps<ProfileStackParamList>

const ProfileButton = ({ buttonProps }: ProfileButtonProps) => {
const navigation = useNavigation<ProfieScreenProp>()
return (
<CustomButton
variant="gray200"
fullWidth
height={80}
borderRadius={20}
flexDirection="row"
justifyContent="space-between"
mb={10}
onPress={() => buttonProps.path && navigation.navigate(buttonProps.path)}
>
...
</CustomButton>
)
}

이런 에러가 발생한다.. 그런데 또 동작은 된다 😞

console로 navigation을 찍어보니

navigate가 들어있다.. 도대체 뭐야?

이리저리 검색해보다가 NativeStackNavigationProp가 눈에 들어왔다.

이거다!

NativeStackScreenProps 와 NativeStackNavigationProp

  1. NativeStackScreenProps

NativeStackScreenProps는 스크린 컴포넌트의 props 타입을 정의하는 제네릭 타입입니다.
일반적으로 스크린 컴포넌트의 타입을 작성할 때 사용됩니다. React.FC와 같은 방식으로 사용할 수 있습니다.

1
2
3
4
5
6
7
8
9
type ProfileScreenProps = NativeStackScreenProps<ProfileStackParamList, 'ProfileScreen'>;

const ProfileScreen = ({ navigation }:ProfileScreenProps) => {
// 스크린 컴포넌트의 props에서 navigation을 사용할 수 있습니다.

return (
// 스크린 컴포넌트의 JSX 코드
);
};
  1. NativeStackNavigationProp은

NativeStackNavigationProp은 네비게이션 프로퍼티(navigation 객체)의 타입을 정의하는 제네릭 타입입니다.
일반적으로 useNavigation 훅 또는 withNavigation 고차 컴포넌트와 함께 사용됩니다.

1
2
3
4
5
6
7
8
9
type ProfileScreenNavigationProp = NativeStackNavigationProp<ProfileStackParamList, 'ProfileScreen'>;

const ProfileScreen = () => {
const navigation = useNavigation<ProfileScreenNavigationProp>();

return (
// JSX 코드
);
};

GPT가 차이점에 대해 설명해주었다.. 아하

NativeStackScreenProps은 props로 navigation을 이용하고 NativeStackNavigationProp은 useNavigation을 이용한다.