reactjs - 如何在带有 typescript 的函数中接受 React.Component 参数?

标签 reactjs generics typescript types

当我将 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>;
    }
}

我想做的是创建一个可以接受 PanelLabel 的类型。

我尝试了以下方法:

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/

相关文章:

javascript - 使用 Node mssql 准备语句的事务

c# - 如何使用我的 List<Type> 中的类型?

ios - 无法与 lrettig 的 react-native-stripe 模块链接

reactjs - 尝试导入错误: 'useControlled' is not exported from '@material-ui/core/utils'

javascript - 如何使用 React-Apollo 处理 GraphQL 错误?

C# : Generic factory object instantiation by passing type (type retrieved from another static object)

java - 如何将通用引用分配给提供非通用数组列表的方法

typescript - typescript 代码中的 T[number] 是什么意思?

angular - 类型 'select2' 上不存在属性 'JQuery<HTMLElement>'

node.js - 在 Jenkins 中构建成功,但 AWS-Codebuild 出现插件错误