组件屏幕道具中typescript的react导航类型



组件屏幕中的navigation道具出现警告或错误

export default function FoodMenuList({ navigation }) {}

因为我没有为navigation分配类型

Binding element 'navigation' implicitly has an 'any'

我试着搜索导航道具类型以进行反应导航,但我找不到

什么是react导航道具类型?

或者可能是?

export default function FoodMenuList({ navigation }: {navigation: {navigate:Function}}) {}

或者可能有更好的解决方案?

根据react navigation提供的文档https://reactnavigation.org/docs/typescript/#type-检查屏幕

要键入检查屏幕,我们需要对屏幕接收到的导航道具和路线道具进行注释。React Navigation中的navigator包导出一个通用类型,以定义来自相应navigator的导航和路线道具的类型。

例如,您可以将NativeStackScreenProps用于Native Stack Navigator。

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'>;

这允许我们键入检查路线名称和您正在使用导航、推送等导航的参数。当前路线的名称对于在route.params中键入检查参数和调用setParams时是必要的。

然后您可以使用上面定义的Props类型来注释组件。

对于功能组件:

function ProfileScreen({ route, navigation }: Props) {
// ...
}

@react-navigation/native尝试useNavigation挂钩,检查文档使用导航

useNavigation是一个钩子,用于访问导航对象。当您无法将导航道具直接传递到组件中,或者在嵌套较深的子级的情况下不想传递时,它会很有用。

您也可以编写

interface Props {
navigation: NavigationType;
}
FoodMenuList({ navigation }: Props)

如果你正在使用类组件,或者你不习惯使用useNavigation

最新更新