![](/img/trans.png)
[英]How to use globally registered components in JSX/TSX without importing?
[英]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> {
我同意這個錯誤令人困惑。
本質上,這是由於未正確指定SomeComponent
的Props
類型,導致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; }; }'
部分,看起來極像是屬性(又名道具)您在使用時指定SomeComponent
在OtherComponent.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.