Reactjs 如何在带有typescript的函数中接受React.Component参数?
当我使用React with TypeScript时,我通常创建一个ES6类来定义一个组件,如下所示:Reactjs 如何在带有typescript的函数中接受React.Component参数?,reactjs,generics,typescript,types,Reactjs,Generics,Typescript,Types,当我使用React with TypeScript时,我通常创建一个ES6类来定义一个组件,如下所示: import * as React from 'react'; interface TextProps { text: string; } export class Panel extends React.Component<TextProps, any> { constructor(props: TextProps) { super(props);
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>;
}
}
这显示React.createElement(组件,
参数)上的编译器错误,但代码运行正常
如何定义类型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 });
}
键入TextComp=new(…args:any[])=>React.Component;
函数创建(组件:TextComp,文本:string){
返回React.createElement(组件,{text:text});
}
根本原因与中解释的相同,您需要的是:
type TextComp = new(...args: any[]) => React.Component<TextProps, any>;
function create(component: TextComp, text: string) {
return React.createElement(component, { text: text });
}
键入TextComp=new(…args:any[])=>React.Component;
函数创建(组件:TextComp,文本:string){
返回React.createElement(组件,{text:text});
}
根本原因与中解释的相同非常酷!您能更进一步并接受React无状态组件吗…只需像
type Stateless=(props:TextProps)这样的函数=>JSX.Element;
?当我试图将您的TextComp类型与我的无状态类型合并时,React.createElement
再次向我抱怨:/非常酷!您能更进一步并接受React无状态组件吗?只需一个类似于type无状态=(props:TextProps)的函数即可=>JSX.Element;
?当我试图将您的TextComp类型与我的无状态类型合并时,React.createElement
再次向我抱怨:/