簡體   English   中英

在React Native中的其他.tsx組件中使用.tsx組件

[英]Using .tsx components in other .tsx components in React Native

我正在自學在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組件? 還是有其他方法可以做到這一點?

您需要將style定義為SomeComponent接受的道具:

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

interface Props {
  style: CSSProperties;
}

export default class SomeComponent extends Component<Props> {

我同意這個錯誤令人困惑。

有什么問題?

本質上,這是由於未正確指定SomeComponentProps類型,導致TypeScript假定了最基本的最小類型定義,其中不包含style屬性。

我如何解決它?

為您希望被SomeComponent接受的道具添加一個接口,其方式與您之前使用PropTypes所做的PropTypes

//SomeComponent.tsx

interface SomeComponentProps {
    style: React.CSSProperties;
}

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

您是如何知道的?

有一些線索。 第一個是Type '{ style: { flex: number; }; }' Type '{ style: { flex: number; }; }' Type '{ style: { flex: number; }; }'部分,看起來極像是屬性(又名道具)您在使用時指定SomeComponentOtherComponent.tsx 因此,它可能與SomeComponent道具有關。

錯誤的下一部分說is not assignable to type ,確認TypeScript認為道具的類型與它對SomeComponent了解SomeComponent

錯誤的最后一部分是最令人困惑的地方,它列出了類型'IntrinsicAttributes & IntrinsicClassAttributes<SomeComponent> & Readonly<{}> & Readonly<{ children?: ReactNode; }>' 'IntrinsicAttributes & IntrinsicClassAttributes<SomeComponent> & Readonly<{}> & Readonly<{ children?: ReactNode; }>' 在React代碼中搜索IntrinsicAttributes可以使我看到它確實與組件期望的屬性的基本類型有關(我在node_modules/@types/react/index.d.ts找到了它的類型定義,反應)。

將所有這些線索與如何使用React.Component的兩個可選泛型類型參數在TypeScript中強力鍵入React.Component和自定義react組件的狀態的先驗知識相結合,可以得出最終的解決方案。

希望您現在能更有能力解密將來同樣令人困惑的錯誤消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM