如果作为参数传递并分配给变量,则在 TypeScript 中反应组件; TS2604:JSX 元素类型没有任何构造或调用签名

React component in TypeScript if passed as parameter and assigned to variable; TS2604: JSX element type does not have any construct or call signatures

我正在尝试处理工厂中传递的 React 元素的道具,但我不能,因为我收到打字稿错误:

TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures.

我的子组件:

interface BlockTitleType {
  title: string,
  children?: React.ReactNode
}

const MainContactBlock: React.FC<BlockTitleType> = (e: BlockTitleType) => <div>{e.title}</div>;

我的父组件:

const factory = new TabBlockFactory(MainContactBlock);

const ContactBlocks: React.FC = () => <>factory.createBlock('test title')}</>

我的工厂:

interface BlockType {
  title: string
}

class TabBlockFactory {
  private mainBlock: React.ReactNode;

  constructor(mainBloc: React.FC) {
    this.mainBlock = mainBloc;
  }

  createBlock = ({title}: BlockType) => {
// the error occurs here: 
// TS2604: JSX element type 'this.extraBlock' does not have any construct or call signatures.
   return <this.mainBlock title={title}/>
  }
}

它只适用于任何类型,但它是一个反模式:(

更新:

我也试过 React.Component、React.ReactElement、JSX.Elements

我已经尝试了@Yuval 的所有 3 个修复:

  1. 没有效果 - 重命名 class 变量 this.mainBlock -> this.MainBlock;

  2. 没有效果-引入了中间变量

const Component = this.mainBloc;
return <Component title={title} />;
  1. 成功帮助了我 - private MainBlock: React.ComponentType<BlockTitleType>; 正如@Yuval 提议的那样。

TLDR:working sandbox link

所以您的代码存在一些问题:

  1. 您正在使用类型 React.ReactNode 来表示组件,但它不起作用。我建议您使用 React.ComponentType<PROPS> 表示 React 组件。 所以在你的情况下将是 ComponentType<BlockTitleType>

  2. <this.mainBlock /> 有问题,React 不喜欢不以大写字母开头的组件,而且它同时访问 this 属性时间,所以把它分成两行,像这样:

const Component = this.mainBloc;
return <Component title={title} />;
  1. 除此之外,我添加了一些小的语法修复和小的改进

    • 工厂中的快速赋值和声明class
    • ContactBlocks
    • 中缺少 {