当我将 React 与 TypeScript 一起使用时,我通常会创建一个 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>;
}
}
我想做的是创建一个可以接受 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 编译此代码时不会出错?
最佳答案
你要的是这个:
type TextComp = new(...args: any[]) => React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
根本原因与 What does the error "JSX element type '...' does not have any construct or call signatures" mean? 中解释的相同
关于reactjs - 如何在带有 typescript 的函数中接受 React.Component 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42847757/