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