0
當我用打字稿反應,我通常會創建一個ES6類來定義,像這樣的組件:如何使用打字機在函數中接受React.Component參數?
import * as React from 'react';
interface TextProps { text: string; }
export class Panel extends React.Component<TextProps, any> {
constructor(props: TextProps) {
super(props);
}
render() {
return <div className="panel">{this.props.text}</div>;
}
}
export class Label extends React.Component<TextProps, any> {
constructor(props: TextProps) {
super(props);
}
render() {
return <span className="label">{this.props.text}</span>;
}
}
我希望做的是建立一個類型,將同時接受一個Panel
或Label
。
我試過如下:
type TextComp = React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
這顯示了React.createElement(component,
參數編譯器錯誤,但代碼運行正常。
如何定義類型TextComp
,以便此代碼使用TypeScript版本2.2.1編譯時沒有錯誤?
非常酷的解釋!你可以更進一步,也可以接受React Stateless組件......簡單的像'type type Stateless =(props:TextProps)=> JSX.Element;'?當我試圖將你的TextComp類型和我的無狀態類型聯合起來時,'React.createElement'再次對我抱怨:/ – styfle