[英]How do I write a type definition for a a sub class (React.Component) in typescript?
[英]How do I create a TypeScript type definition for a stateless React component?
我正在嘗試為現有的無狀態 React組件創建類型定義,因此我可以自動生成文檔並提高團隊工具中的intellisense。
示例組件可能如下所示:
myComponent.js
import React from 'react';
export const MyComponent = ({ prop1, prop2, prop3 }) => (
<div>
{ prop1 ? prop2 : prop3 }
</div>
);
我希望我的類型定義為:
看一下使用TypeScript創建React組件的這個例子,我發現了類型: React.SFC
。
我試着在我的定義中使用它:
index.d.ts
declare module "MyComponent" {
import React from 'react';
interface MyComponentProps {
prop1: boolean;
prop2?: string;
prop3?: string;
}
export const MyComponent = React.SFC<MyComponentProps>
}
但我得到了linting錯誤[ts] '(' expected.
我是TypeScript的新手,我顯然遺漏了一些東西,但我找不到任何關於為無狀態組件創建類型定義的文章。
編輯為了清楚起見,我不想在TypeScript中重寫我的組件。 我想為現有的ES6無狀態組件創建一個類型定義文件(* .d.ts)。
經過大量的擺弄,我們已經確定了以下設置。
import React from 'react';
export interface MyComponentProps {
prop1: boolean;
prop2?: string;
prop3?: string;
}
declare const MyComponent: React.SFC<MyComponentProps>
export default MyComponent
靈感來源於: https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/material-ui/index.d.ts
它適用於TypeDoc以及VS Code的intellisense。
我認為export default
是破解智能感知的關鍵。
嘗試這個:
declare module "MyComponent" {
import React from 'react';
interface MyComponentProps {
prop1: boolean;
prop2?: string;
prop3?: string;
}
export const MyComponent: (props: MyComponentProps) => React.SFC<MyComponentProps>
}
從官方React頁面建議類型定義
我認為你需要var MyComponent: React.SFC<MyComponentProps>;
你可以考慮重寫typescript中的現有代碼,只是為了看看tsc會產生什么樣的定義。 然后丟棄代碼並保留定義。
它, :
,不=
。
export const MyComponent:React.SFC<MyComponentProps> = ({ prop1, prop2, prop3 }) => (
<div>
{ prop1 ? prop2 : prop3 }
</div>
);
你可以嘗試這樣的事情。
export type YourComponentType = {
props1,
props2
}
const YourComponent = ({
props1,
props2,
...restProps //additional props if passed to components.
}: YourComponentType) => (
<div>{props1}</div>
)
export default YourComponent;
我正在使用Microsoft提供的react typescript react樣板https://github.com/Microsoft/TypeScript-React-Starter
我在typescript中創建一個無狀態組件,如下所示:
export interface IMyComponentProps {
prop1: string;
prop2: (event: React.MouseEvent) => void;
prop3: number;
}
export class MyComponent extends React.Component<IMyComponentProps> {
render(): JSX.Element {
const {prop1, prop2} = this.props
return (
//My code here
<button>prop1</button>
<button>prop2</button>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.