我正在教自己如何用TypeScript在Reactinative中构建应用程序。作为一个Swift开发人员,JS和TS需要一点时间来适应。
我注意到的一件事是,在呈现方法的另一个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组件?或者还有其他方法可以做到这一点?
发布于 2019-05-14 21:28:00
我同意这个错误令人困惑。
有什么问题吗?
本质上,这是由于没有正确地指定Props of SomeComponent的类型,导致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; }; }'部分,它看起来非常像属性(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,将使我找到最终的解决方案。
希望您现在更有能力在将来破译类似的混淆错误消息。
发布于 2019-05-14 21:27:55
您需要将style定义为您的SomeComponent所接受的支柱:
import React, { Component, CSSProperties } from "react";
interface Props {
style: CSSProperties;
}
export default class SomeComponent extends Component<Props> {https://stackoverflow.com/questions/56138668
复制相似问题