【问题标题】:React Typescript: Cannot assign component to elementReact Typescript:无法将组件分配给元素
【发布时间】:2021-06-30 22:04:15
【问题描述】:

我需要将我的 JSX 组件 (FC) 映射到一个对象中以进行动态渲染。 到目前为止,这是我想出的:

对象接口

interface Mappings {
  EC2: {
    component: React.FC<{}>;
    name: string;
    description: string;
  };
}

export enum ResourcesEnum {
  EC2 = 'EC2',
  S3 = 'S3',
}

同一文件中定义的映射对象:

错误消息:

Type 'Element' is not assignable to type 'FC<{}>'.
Type 'Element' provides no match for the signature 
'(props: { children?: ReactNode; }, context?: any): ReactElement<any, any> | null'.

非常感谢!

【问题讨论】:

  • &lt;EC2 /&gt; 的类型是JSX.Element,所以你可以用正确的类型修改你的Mappings 接口吗?

标签: javascript node.js reactjs typescript react-native


【解决方案1】:

React.FC&lt;{}&gt; 类型描述组件本身,而不是组件的实例。 Mappings 期望您的对象包含 component: EC2 而不是 component: &lt;EC2 /&gt;

您要么需要更改值以匹配您的类型,要么更改您的类型以匹配您的值。无论哪种方式都很好。如果你想保留component: &lt;EC2 /&gt;,那么你的类型需要是component: JSX.Element

【讨论】:

    【解决方案2】:

    您需要将组件的类型更改为JSX.ElementElement,因为&lt;EC2 /&gt;JSX

    interface Mappings {
      EC2: {
        component: JSX.Element;
        name: string;
        description: string;
      };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多