【问题标题】:type a React component in typescript在 typescript 中输入一个 React 组件
【发布时间】:2020-06-24 13:08:29
【问题描述】:

我有以下 SSCCE:

function just_accept(x: React.ComponentType<any>): void {
}


class A extends React.Component<any> {
  constructor(props: any) {
    super(props);
  }
  render() {return <span>foo</span>;}
}

just_accept(A); // <-- this is the offending line in the typescript message

这给了我以下打字稿错误:

TS2345:“typeof A”类型的参数不可分配给参数 'ComponentType' 类型。类型“typeof A”不可分配给 键入“组件类”。 类型 'A' 缺少来自类型 'Component' 的以下属性:context、setState、forceUpdate、props 和 还有 2 个。

将参数x 声明为React.ComponentClass&lt;any, any&gt; 类型没有区别。

【问题讨论】:

  • just_accept(A.name); 有效吗?可能不是?我只是在猜测:P 你的函数需要一个React.ComponentType&lt;any&gt;,但你传递了一个React.Component&lt;any&gt;

标签: reactjs typescript


【解决方案1】:

这是由于:

const React = require('react');

一旦替换为:

import React from 'react';

...事情按预期进行。

【讨论】:

    猜你喜欢
    • 2020-10-22
    • 2021-05-29
    • 1970-01-01
    • 2016-11-01
    • 2020-10-07
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多