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

如何使用模板字面量定义图标?React赋值时出现TS类型错误如何解决

报错原因

你收到的类型报错如下:

Type 'boolean' is not assignable to type 'ReactElement<any, string | JSXElementConstructor>'.ts(2322)
component.tsx(7, 3): The expected type comes from property 'icon' which is declared here on type 'IntrinsicAttributes & SocialButtonProps'
(JSX attribute) icon: React.ReactElement<any, string | React.JSXElementConstructor>

触发报错的核心原因是你写的<${platform.name}Logo />不符合JSX语法规则:JSX标签名不支持直接传入模板字符串,这段无效语法在运行时会返回布尔值,和icon属性要求的ReactElement类型不匹配。
除此之外你的代码还有两处隐藏问题:

  • map回调使用了大括号包裹但没有写return语句,会导致返回undefined,组件无法渲染
  • onClick回调里写死了SocialPlatform.BEHANCE,所有按钮点击都会选中同一个平台
正确实现方案

推荐用预定义图标映射表的方式实现,类型安全且无运行时风险:

  1. 首先导入所有用到的社交图标组件,定义映射表
// 导入你用到的所有平台Logo组件
import BehanceLogo from './icons/BehanceLogo'
import GithubLogo from './icons/GithubLogo'
import TwitterLogo from './icons/TwitterLogo'
// 其他需要的图标组件省略

// 定义和你现有SocialPlatform枚举对应的联合类型
type PlatformName = keyof typeof SocialPlatform

// 建立平台名称到组件的映射关系
const LogoMap: Record<PlatformName, React.FC> = {
  BEHANCE: BehanceLogo,
  GITHUB: GithubLogo,
  TWITTER: TwitterLogo,
  // 其他平台对应关系按需补充
}
  1. 修改渲染部分代码
<Grid item>
  {attributesState.attributesData.socialPlatform.map((platform) => {
    // 取出对应Logo组件,注意组件名必须首字母大写
    const CurrentLogo = LogoMap[platform.name as PlatformName]
    return (
      <SocialButton
        isSelected={socialPlatform === platform.name}
        icon={<CurrentLogo />}
        onClick={() => {
          // 改成动态设置当前选中的平台
          setSocialPlatform(platform.name as SocialPlatform)
        }}
      />
    )
  })}
</Grid>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 00:51:02