【问题标题】:How can I accept a React.Component parameter in a function with typescript?如何在带有打字稿的函数中接受 React.Component 参数?
【发布时间】:2017-08-08 10:26:09
【问题描述】:

当我将 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 编译此代码而不会出错?

【问题讨论】:

    标签: reactjs generics typescript types


    【解决方案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?中解释的相同

    【讨论】:

    • 非常酷!你能更进一步,也接受 React 无状态组件……只是像 type type Stateless = (props: TextProps) =&gt; JSX.Element; 这样的函数吗?当我尝试将您的 TextComp 类型与我的无状态类型结合时,React.createElement 再次向我抱怨:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 2021-11-13
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    相关资源
    最近更新 更多