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

组件返回数组时如何正确适配React.FC类型?

问题:使用React.FC定义返回数组的组件时出现类型错误

项目要求使用React.FC而非直接类型定义组件,以下代码可正常运行:

interface IConfigActions {
  iconColor: string;
}
const ConfigActions = ({iconColor}: IConfigActions) => {
  return (
    [
      { id: 1, icon: <MediaSVG style={{ fill: iconColor }} /> },
      { id: 2, icon: <GifSVG style={{ fill: iconColor }} /> },
      { id: 3, icon: <PollSVG style={{ fill: iconColor }} /> },
      { id: 4, icon: <EmojiSVG style={{ fill: iconColor }} /> },
      { id: 5, icon: <ScheduleSVG style={{ fill: iconColor }} /> },
    ]
  )
}

但改用React.FC类型定义组件时出现错误:

const ConfigActions:FC<IConfigActions> = ({iconColor}) => {
  return (
    [
      { id: 1, icon: <MediaSVG style={{ fill: iconColor }} /> },
      { id: 2, icon: <GifSVG style={{ fill: iconColor }} /> },
      { id: 3, icon: <PollSVG style={{ fill: iconColor }} /> },
      { id: 4, icon: <EmojiSVG style={{ fill: iconColor }} /> },
      { id: 5, icon: <ScheduleSVG style={{ fill: iconColor }} /> },
    ]
  )
}

错误提示:

类型“({ iconColor }: IConfigActions) => { id: number; icon: Element; }[]”无法赋值给类型“FC”。
类型“{ id: number; icon: Element; }[]”缺少类型“ReactElement<any, any>”的以下属性:type、props、key ts(2322)


解决方案

React.FC类型要求组件返回值必须是React元素(ReactElement)、null,或者符合规范的React元素数组,当前返回的是普通对象数组,并非React可渲染的元素类型,因此类型不匹配。可根据实际使用场景选择以下两种修改方式:

方式1:调整为返回React可渲染内容

如果该函数是作为React组件被渲染(如<ConfigActions />),必须返回React可识别的渲染内容。可将数组转换为React元素数组并包裹在Fragment中,或直接返回带key的元素数组:

import { FC, Fragment } from 'react';

interface IConfigActions {
  iconColor: string;
}

const ConfigActions: FC<IConfigActions> = ({ iconColor }) => {
  return (
    <Fragment>
      {[
        { id: 1, Icon: MediaSVG },
        { id: 2, Icon: GifSVG },
        { id: 3, Icon: PollSVG },
        { id: 4, Icon: EmojiSVG },
        { id: 5, Icon: ScheduleSVG },
      ].map(({ id, Icon }) => (
        <Icon key={id} style={{ fill: iconColor }} />
      ))}
    </Fragment>
  );
};

方式2:自定义组件类型(保留返回对象数组)

如果该函数仅用于生成配置数据而非直接渲染,本质不属于React组件,但项目要求必须用类似组件的类型定义,可自定义类型替代React.FC:

import { FC } from 'react';

interface IConfigActions {
  iconColor: string;
}

// 定义返回值的类型
type ConfigItem = { id: number; icon: React.ReactElement };

// 自定义组件类型,适配返回对象数组的场景
type ConfigActionsComponent = (props: IConfigActions) => ConfigItem[];

const ConfigActions: ConfigActionsComponent = ({ iconColor }) => {
  return [
    { id: 1, icon: <MediaSVG style={{ fill: iconColor }} /> },
    { id: 2, icon: <GifSVG style={{ fill: iconColor }} /> },
    { id: 3, icon: <PollSVG style={{ fill: iconColor }} /> },
    { id: 4, icon: <EmojiSVG style={{ fill: iconColor }} /> },
    { id: 5, icon: <ScheduleSVG style={{ fill: iconColor }} /> },
  ];
};

注意:若需将该函数作为React组件渲染,方式1是唯一符合React规范的选择。

内容的提问来源于stack exchange,提问作者NaN-Simon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:05:27