【问题标题】:TypeScript Property 'navigation' is missing in type but required in type 'Props' React Native类型中缺少 TypeScript 属性“导航”,但类型“道具”React Native 中需要
【发布时间】:2020-05-30 04:26:35
【问题描述】:

在 React Native 应用程序中,我知道当您将 RootNavigator 传递到 createAppContainer 中并将其导出时,导航 prop 会隐式地在所有子组件中可用。

export default createAppContainer(AppNavigator);

我有这个组件应该使用导航道具导航到另一个屏幕。我为这个组件的 props 定义了一个接口,如下所示:

ComponentA 的props 接口:

interface Props {
  count: number;
  navigation: NavigationStackProp<{quizId: number}>;
}

现在我像这样渲染 ComponentA:

...
render() {
    return (
        <ComponentA count={0} /> // TypeScript screams here that I am not passing the navigation props
    );
}

如果我像这样使用 ComponentA 传递导航道具:

<ComponentA count={0} navigation={props.navigation} />

TypeScript 很满意。

因此,我的问题是,我是否必须像这样明确地传递导航道具?我觉得不对。有没有办法可以在这种特殊情况下抑制 TypeScript 警告。

我是 TypeScript 的新手,所以这可能是微不足道的事情,但我将不胜感激。

谢谢

【问题讨论】:

    标签: javascript reactjs typescript react-native


    【解决方案1】:

    您可以通过 ? 使用可选道具

    interface Props {
      count: number;
      navigation?: NavigationStackProp<{quizId: number}>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 2015-12-02
      • 2020-08-24
      • 2022-01-19
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多