首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在React本机中的其他.tsx组件中使用.tsx组件

在React本机中的其他.tsx组件中使用.tsx组件
EN

Stack Overflow用户
提问于 2019-05-14 21:12:01
回答 2查看 1.4K关注 0票数 1

我正在教自己如何用TypeScript在Reactinative中构建应用程序。作为一个Swift开发人员,JS和TS需要一点时间来适应。

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

代码语言:javascript
复制
//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>
    }
}

这将导致以下错误:

代码语言:javascript
复制
Type '{ style: { flex: number; }; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<SomeComponent> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-14 21:28:00

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

有什么问题吗?

本质上,这是由于没有正确地指定Props of SomeComponent的类型,导致TypeScript假定最小类型定义,其中不包括style属性。

我该怎么解决呢?

为您希望被SomeComponent接受的道具添加一个接口,就像您以前使用PropTypes时所做的那样。

代码语言:javascript
复制
//SomeComponent.tsx

interface SomeComponentProps {
    style: React.CSSProperties;
}

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

你是怎么弄明白的?

有几条线索。第一个是Type '{ style: { flex: number; }; }'部分,它看起来非常像属性(a.k.a )。在SomeComponent中使用OtherComponent.tsx时指定。因此,这可能与SomeComponent的道具有关。

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

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

将所有这些线索与如何在TypeScript中强键入道具和自定义react组件的状态的先验知识结合起来,使用两个可选的泛型类型params到React.Component,将使我找到最终的解决方案。

希望您现在更有能力在将来破译类似的混淆错误消息。

票数 1
EN

Stack Overflow用户

发布于 2019-05-14 21:27:55

您需要将style定义为您的SomeComponent所接受的支柱:

代码语言:javascript
复制
import React, { Component, CSSProperties } from "react";

interface Props {
  style: CSSProperties;
}

export default class SomeComponent extends Component<Props> {
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56138668

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档