【问题标题】:React: Using ES6 component in TS component: TS2605: JSX element type 'xxx' is not a constructor function for JSX elementsReact:在 TS 组件中使用 ES6 组件:TS2605:JSX 元素类型“xxx”不是 JSX 元素的构造函数
【发布时间】:2017-07-21 07:12:21
【问题描述】:

我想在另一个 Typescript 组件中使用 ES6 React 组件。

ES6 组件:

class ModelViewer extends Component {
  constructor(props, context) {
    super(props, context);
    //...
  }
// ...
}
export default ModelViewer;

我的消费 TS 组件:

import * as ReactDOM from "react-dom";
import * as React from "react";
import ModelViewer from "./model_viewer/ModelViewer";

export class Viewer extends React.Component<any, any> {
    render() {
        return (
                <div>
                    <ModelViewer />
                </div>
        );
    }
}

TSC 的选项是:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true
    }
}

现在我收到错误TS2605: JSX element type 'ModelViewer' is not a constructor function for JSX elements.

尽管设置了"allowJS": true,我还需要提供类型吗?我尝试了不同的导入方式,但没有区别。

【问题讨论】:

  • 完整的错误是 App.tsx(11,17): error TS2605: JSX element type 'ModelViewer' is not a constructor function for JSX elements. Property 'setState' is missing in type 'ModelViewer'. 我认为 TSC 不理解 extends Component... 在您的 ES6 组件中尝试 import {Component} from "react"
  • 我还注意到您的模型查看器类中缺少“React.Component”。除此之外,只要导入路径正确,您就不会再收到与“不是构造函数”相关的错误。
  • 你找到解决这个问题的方法了吗?我有同样的问题

标签: javascript reactjs typescript


【解决方案1】:

作为一种蛮力方法,我使用自定义类型文件满足了 Typescript 编译器。

// typings/custom.d.ts
declare module "*";

并告诉我的 tsconfig.json 中的编译器读取我的自定义类型:

// tsconfig.json
{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "removeComments": true,
        "sourceMap": true,
        "allowJs": true,
        "watch": true,
        "outDir": "./dist/",
        "jsx": "react",
        "experimentalDecorators": true,
        "allowSyntheticDefaultImports": true,
        "typeRoots": [
             "./typings",
             "node_modules/@types"
         ]
    }
}

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 2019-11-24
    • 2020-05-31
    • 2019-05-29
    • 2019-03-06
    • 2019-05-18
    • 2020-08-14
    • 2019-07-21
    相关资源
    最近更新 更多