带有 Typescript TS2604 错误的动态导入 ES6 React 组件?

Dynamic Import ES6 React Component with Typescript TS2604 error?

我正在尝试从这样的模块中动态导入 React 组件:

state: {
  OsdComponent: React.Component<any, any>
}

constructor(props) {
  super(props)
  this.state = {
    OsdComponent: null,
  }
}

async componentWillMount() {
   const {OsdComponent} = await import(`manifest-viewer`)
   this.setState({OsdComponent})
}

然后尝试在渲染中像这样使用它:

render() {
   const {OsdComponent} = this.state
   if (OsdComponent) {
     <OsdComponent/>
   }
}

但 Typescript 编译失败并显示“TS2604:JSX 元素类型 'OsdComponent' 没有任何构造或调用签名。”

该代码在另一个未使用 Typescript 编译的模块中运行。

<Foo .../> 语法中,Foo 必须是 type 的组件(即 React.ComponentType<P> 类型的 [=13] =]);例如,Foo 可能是您定义的组件 class 的名称。 React 将在渲染期间为您创建一个组件类型的实例。您不会传入自己创建的组件实例(例如 let Bar = new Foo(); <Bar .../>);那是没有意义的。但这就是您尝试使用 OsdComponent 所做的事情,因为您已将其类型声明为 React.Component<any, any>。将类型更改为 React.ComponentType<any, any>(这可能是您的动态导入实际上 returns)并且错误应该消失。 (当然,最好至少指定道具类型而不是使用any。)