sty*_*fle 1 generics types typescript reactjs
当我在 TypeScript 中使用 React 时,我通常会创建一个 ES6 类来定义一个组件,如下所示:
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>;
}
}
Run Code Online (Sandbox Code Playgroud)
我想做的是创建一个可以接受 aPanel
或 a 的类型Label
。
我尝试了以下方法:
type TextComp = React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
Run Code Online (Sandbox Code Playgroud)
这显示React.createElement(component,
参数上的编译器错误,但代码运行正常。
如何定义类型TextComp
,以便使用 TypeScript 2.2.1 版编译此代码时不会出错?
你想要的是这个:
type TextComp = new(...args: any[]) => React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
Run Code Online (Sandbox Code Playgroud)
根本原因与错误“JSX 元素类型 '...' 没有任何构造或调用签名”是什么意思中的解释相同?
归档时间: |
|
查看次数: |
6290 次 |
最近记录: |