【问题标题】:Using .tsx components in other .tsx components in React Native在 React Native 中的其他 .tsx 组件中使用 .tsx 组件
【发布时间】:2019-10-01 23:13:35
【问题描述】:

我正在自学在 React Native 中使用 TypeScript 构建应用程序。作为 Swift 开发者,JS 和 TS 需要一点时间来适应。

我注意到的一件事是,似乎不可能在 Render 方法中使用我在另一个 tsx 文件中的 tsx 文件中编写的组件。

//SomeComponent.tsx

export default class SomeComponent extends Component {
    //all my logic
}

//OtherComponent.tsx
export default class ScoreTable extends Component {
    //logic
    render() {

      <SomeComponent style={{flex: 1}}></SomeComponent>
    }
}

这会给我以下错误:

Type '{ style: { flex: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<SomeComponent> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

我可以通过简单地将我的 tsx SomeComponent 转换为 .js 组件来解决这个问题,但我真的很喜欢 tsx 语法。 所以我的问题是为什么我不能在其他 tsx 组件中使用 .tsx 组件?还是有其他方法可以做到这一点?

【问题讨论】:

  • 如何在OtherComponent.tsx 中导入SomeComponent
  • 从 '../../../Views/SomeComponent' 导入 SomeComponent。我已经看到由于在线导入错误导致的其他问题,并验证这不是这里的问题

标签: javascript typescript react-native react-tsx


【解决方案1】:

我同意这个错误令人困惑。

有什么问题?

本质上,这是由于没有正确指定 SomeComponentProps 的类型,导致 TypeScript 假定了最简单的类型定义,其中不包含 style 属性。

我该如何解决?

为您希望被 SomeComponent 接受的道具添加一个接口,这与您之前使用 PropTypes 所做的方式大致相同。

//SomeComponent.tsx

interface SomeComponentProps {
    style: React.CSSProperties;
}

export default class SomeComponent extends Component<SomeComponentProps> {
    //all my logic
}

你是怎么知道的?

有一些线索。第一个是Type '{ style: { flex: number; }; }' 部分,它看起来很像您在OtherComponent.tsx 中使用SomeComponent 时指定的属性(也称为道具)。所以它可能与SomeComponent 的道具有关。

错误的下一部分是 is not assignable to type,确认 TypeScript 认为道具的类型与它所知道的 SomeComponent 不匹配。

错误的最后一部分是最令人困惑的,它列出了类型'IntrinsicAttributes &amp; IntrinsicClassAttributes&lt;SomeComponent&gt; &amp; Readonly&lt;{}&gt; &amp; Readonly&lt;{ children?: ReactNode; }&gt;'。在我的 React 代码中搜索 IntrinsicAttributes 让我看到它确实与组件期望的属性的基本类型有关(我在 node_modules/@types/react/index.d.ts,react 的类型定义中找到它)。

将所有这些线索与关于如何使用 React.Component 的两个可选泛型类型参数在 TypeScript 中强类型化自定义 React 组件的 props 和状态的先验知识相结合,我找到了最终解决方案。

希望您现在感到更有能力在未来破译同样令人困惑的错误消息。

【讨论】:

  • 太棒了!感谢您的全面解释
【解决方案2】:

您需要将style 定义为您的SomeComponent 接受的道具:

import React, { Component, CSSProperties } from "react";

interface Props {
  style: CSSProperties;
}

export default class SomeComponent extends Component<Props> {

【讨论】:

    猜你喜欢
    • 2016-11-01
    • 2022-11-05
    • 1970-01-01
    • 2020-04-08
    • 2021-10-04
    • 2017-04-27
    • 2017-01-31
    • 2021-07-10
    • 2020-12-12
    相关资源
    最近更新 更多