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

TypeScript 中动态构建React元素时JSX无构造签名报错如何解决?

问题原因
  • 类型匹配错误:你定义的overrides字段是包含Typography属性的对象,类型为{ Typography: React.ComponentType },但代码中直接将整个overrides对象作为组件赋值给CustomTypography,对象本身不满足JSX组件的类型要求,因此抛出JSX element type 'CustomTypography' does not have any construct or call signatures的报错。
  • ref引用错误:当前StyledTypography是普通函数组件,没有接收ref参数,内部直接使用ref会触发未定义的报错。
修复方案

你可以根据是否需要支持ref传递选择对应方案:

方案1:保留ref传递能力

用forwardRef包裹组件接收外部传入的ref,同时正确提取overrides内的Typography组件:

import React, { forwardRef } from 'react';
// 需确保已正确引入TypographyProps、MainTypography的相关定义

interface StyledTypographyProps extends TypographyProps {
    overrides?: { Typography: React.ComponentType };
}

export const StyledTypography = forwardRef<HTMLElement, StyledTypographyProps>((props, ref) => {
    const { children, overrides, ...typographyProps } = props;
    // 提取overrides对象内的Typography组件,兜底使用MainTypography
    const CustomTypography = overrides?.Typography ?? MainTypography;

    return (
        <CustomTypography ref={ref} {...typographyProps}>
            {children}
        </CustomTypography>
    )
});

如果MainTypography有明确的根元素类型,可以将forwardRef的第一个泛型参数HTMLElement替换为对应的具体类型(比如HTMLParagraphElement、HTMLSpanElement)。

方案2:不需要ref传递

直接删除JSX中的ref属性即可,无需使用forwardRef:

interface StyledTypographyProps extends TypographyProps {
    overrides?: { Typography: React.ComponentType };
}

export const StyledTypography: React.FunctionComponent<StyledTypographyProps> = (props) => {
    const { children, overrides, ...typographyProps } = props;
    const CustomTypography = overrides?.Typography ?? MainTypography;

    return (
        <CustomTypography {...typographyProps}>
            {children}
        </CustomTypography>
    )
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 23:06:05