You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中任意类型组件的TypeScript类型定义该如何选择?

问题:如何定义任意React组件的TypeScript类型?

我想要定义一种组件类型,无论它接收多少props,是类组件还是函数组件,甚至不管它返回JSX元素、null还是任意字符串都可以。我只想表示“一个组件”——也就是React定义的可能包含key属性和ref属性的任意内容。

我尝试使用React.Component:

function Ramadan(){
  return <></>
}

const templatesMap: { [key: string]: React.Component } = {
  ramadan: Ramadan,
  adha: () => <></>,
  fitir: () => <></>,
  unset: () => <></>,
  mothers: () => <></>,
  birthDay: () => <></>,
}

但TypeScript报错:

Type '() => Element' is not assignable to type 'Component<{}, {}, any>'.ts(2322)
WriteContent.tsx(10, 25): The expected type comes from this index signature.

我想知道这种任意组件的正确类型是什么?


解决方案

你用错类型了——React.Component是类组件实例的类型,不是组件本身的构造函数/函数组件类型,所以函数组件肯定没法赋值给它。

要表示任意类组件或函数组件,不管props和返回值,正确的类型是React.ComponentType<any>:

  • ComponentType是React内置的类型别名,它涵盖了ComponentClass(类组件构造函数)和FunctionComponent(函数组件)两种类型
  • 泛型参数any表示允许组件接收任意props,完全符合你“不管接收多少props”的需求

修改后的代码示例:

import React from 'react';

function Ramadan(){
  return <></>
}

// 也支持类组件
class EidAdha extends React.Component {
  render() {
    return <div>Eid Adha</div>;
  }
}

const templatesMap: { [key: string]: React.ComponentType<any> } = {
  ramadan: Ramadan,
  adha: EidAdha,
  fitir: () => <></>,
  unset: () => null, // 支持返回null
  mothers: () => 'Happy Mothers Day', // 支持返回字符串
  birthDay: () => <div>Birthday</div>,
}

如果你的场景还需要包含原生HTML元素(比如把'div'当作组件值),可以用更宽泛的React.ElementType,它包含了ComponentType和所有HTML标签名的字符串类型。


内容的提问来源于stack exchange,提问作者Islam Y-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:02:22