React Native 键入嵌套的导航器时出现问题,导航器无法响应

50pmv0ei  于 2022-11-17  发布在  React
关注(0)|答案(2)|浏览(190)

我有一个选项卡导航器,它有HomeProfile作为屏幕。Home是一个堆栈导航器,它包含RestaurantDetailsRestaurantList作为屏幕。
我有一个ButtonRestaurantList屏幕中。我想导航到RestaurantDetails
Button.tsx

const Button = ({name}) => {
  const navigation = useNavigation()
  const onPress = () => {
    navigation.navigate("RestaurantDetails", {name})
  }
  return (
    <TouchableOpacity onPress={onPress}>
    </TouchableOpacity>
   
  )
}

问题是 typescript 抱怨

Argument of type '["RestaurantDetails", { name: string}]' is not assignable to parameter of type '[screen: "Home", params: NavigatorScreenParams<HomeStackParamList, Readonly<{ key: string; index: number; routeNames: string[]; history?: unknown[] | undefined; routes: NavigationRoute<ParamListBase, string>[]; type: string; stale: false; }>>] | [screen: ...] | [screen: ...] | [screen: ...] | [screen: ...]'.
  Type '["RestaurantDetails", { name: string}]' is not assignable to type '[screen: "Profile", params: undefined]'.
    Type at position 0 in source is not compatible with type at position 0 in target.
      Type '"RestaurantDetails"' is not assignable to type '"Profile"'.

我很确定问题是在RestaurantDetails屏幕上,typescript在TRootParamList而不是HomeStackParamList中查找,因为如果我将RestaurantDetails添加到TRootParamList中,typescript就不会再抱怨了。但是,我不确定如何真正阻止这个问题。
types.ts

import { NavigatorScreenParams } from '@react-navigation/native';

type QueueDetailsParams = {
  name: string
};

type HomeStackParamList = {
  RestaurantDetails: QueueDetailsParams | undefined;
  RestaurantList: undefined
};

type TRootParamList = {
  Home: NavigatorScreenParams<HomeStackParamList>;
  Profile: undefined
};

declare global {
  namespace ReactNavigation {
    interface RootParamList extends TRootParamList {}
  }
}

我知道我可以用下面的替换我的onPress,但我宁愿不这样做。

const onPress = () => {
    navigation.navigate("Home", {screen: "RestaurantDetails", params: {name}})
  }
ee7vknir

ee7vknir1#

当您使用useNavigation挂接时,必须使用StackNavigationProp和包含目标屏幕的参数列表来键入它:

const { navigate } = useNavigation<StackNavigationProp<HomeStackParamList>>();

然后,您可以将其用于参数列表中的任何屏幕:

navigate('RestaurantList');
j8ag8udp

j8ag8udp2#

如果从道具导入导航可以解决您的问题,请告诉我,如果不能,我们可以进一步调试它:

const Button = ({name,navigation}) => {
  const onPress = () => {
    navigation.navigate("RestaurantDetails", {name})
  }
  return (
    <TouchableOpacity onPress={onPress}>
    </TouchableOpacity>
   
  )
}

相关问题