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

React将组件作为props传递渲染时TS2604类型错误如何解决?

解决React组件作为Prop传入时的TS2604类型错误

报错原因

TS2604报错是因为你对ContainerElement的类型定义错误:Component不是可直接作为JSX标签渲染的通用组件类型,无法兼容函数组件、Fragment、Next.js的Head组件这类类型。

修复方案

将ContainerElement的类型替换为React内置的ElementType即可,该类型天生兼容所有可作为JSX标签渲染的内容,完全覆盖你需要的Fragment、Next.jsHead组件等场景。
修改后的完整代码如下:

import type { FC, ElementType } from 'react';

export type SummaryCardProps = {
  site?: string;
  title: string;
  description?: string;
  image?: URL;
  imageAlt?: string;
  ContainerElement: ElementType;
};

export const SummaryCard: FC<SummaryCardProps> = (props) => {
  // 解构后首字母大写,符合JSX标签命名规范,避免ESLint报错
  const { ContainerElement } = props;
  return (
    <ContainerElement>
      <meta name="twitter:card" content="summary" />
      <meta name="twitter:site" content={props.site ? new URL('https://' + props.site).toString() : undefined} />
      <meta name="twitter:title" content={props.title} />
      <meta name="twitter:description" content={props.description ?? "View the album on Flickr."} />
      <meta name="twitter:image" content={props.image?.toString() ?? "https://farm6.staticflickr.com/5510/14338202952_93595258ff_z.jpg"} />
    </ContainerElement>
  );
};

额外优化说明

  • 对可选参数site、description、image增加了兜底处理,避免参数未传入时生成无效内容
  • 将props.ContainerElement解构为大写开头的变量,符合JSX标签必须大写开头的规范,避免部分校验规则抛出错误

内容的提问来源于stack exchange,提问作者Ariel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 19:06:01