【问题标题】:navigation.navigate('Home') showing some error in typescriptnavigation.navigate('Home') 在打字稿中显示一些错误
【发布时间】:2021-10-17 02:57:15
【问题描述】:

当我使用 useNavigation 或从 props { navigation } 使用 navigation.navigate('Home') 在屏幕之间导航时,打字稿返回错误 '"Main"' 类型的参数不可分配给 '{ key: string 类型的参数;参数?:未定义;合并?:布尔值 |不明确的; } | {名称:从不;键?:字符串 |不明确的;参数:从不;合并?:布尔值 |不明确的; }' 是什么意思?

下面是我的代码:

import React from 'react';
import { View } from 'react-native';
import { Button } from 'react-native-paper';
import { useNavigation } from '@react-navigation/native';

const Home: React.FC = () => {
  const navigation = useNavigation();

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button onPress={() => navigation.navigate('Main')}>Navigate</Button>
    </View>
  );
};

export default React.memo(Home);

以前我使用 react navigation v5 并使用该方法查找

感谢您的帮助

【问题讨论】:

标签: react-native react-navigation


【解决方案1】:

也许你想做这样的事情:

export type RootStackParamList = {
  Main: undefined;
  Home: undefined;
};

const Stack = createStackNavigator<RootStackParamList>();

export const RootNavigator = () => {
  return (
    <Stack.Navigator initialRouteName="Main">
      <Stack.Screen
        name="Main"
        component={Main}
      />
      <Stack.Screen
        name="Home"
        component={Home}
      />
    </Stack.Navigator>
  );
};

然后在你的代码中做这样的事情:

type homeScreenProp = StackNavigationProp<RootStackParamList, 'Home'>;

const Home: React.FC = () => {
  const navigation = useNavigation<homeScreenProp>();

  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Button onPress={() => navigation.navigate('Main')}>Navigate</Button>
    </View>
  );
};

【讨论】:

  • 你也应该做一些解释。让其他人更容易理解问题和解决方案
  • 好的,也许这篇文章可以提供帮助。 benjaminwoojang.medium.com/…
  • 我只是这样做,但导航功能不起作用总是在 Typescript 中返回错误消息,但在应用程序中没有错误
  • Cannot find name 'RootStackParamList'. 我在尝试时遇到了这个错误
  • @RahmanHaroon 您需要从第一个文件中导入它。 (此处导出:export type RootStackParamList
【解决方案2】:

这是因为您必须指定此类型,因为这将确保类型安全。

解决方案:

1 - 类型检查导航器

// root.routes.tsx    

import { createStackNavigator } from '@react-navigation/stack';
    
export type RootStackParamList = {
  Home: undefined;
  Profile: { userId: string };
  Feed: { sort: 'latest' | 'top' } | undefined;
};
    
const RootStack = createStackNavigator<RootStackParamList>();

2 - 为您的根导航器指定全局类型

// navigation.d.ts

import { RootStackParamList } from '../routes/root.routes';

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

3 - 使用它!

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

const navigation = useNavigation();

navigation.navigate('Home');

参考:

【讨论】:

  • 成功了! @ambegossi
猜你喜欢
  • 2016-10-25
  • 2022-08-16
  • 2017-02-26
  • 1970-01-01
  • 2018-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多