gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 00:47:15 24 4
gpt4 key购买 nike

当我将 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com