網站搜尋

javascript - React:在 TS 組件中使用 ES6 組件:TS2605:JSX 元素類型 'xxx' 不是 JSX 元素的構造函數


我想在另一個 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 元素類型 'ModelViewer' 不是 JSX 元素的構造函數。

即使我已設定 "allowJS": true,我是否仍需要提供類型定義?我已嘗試過不同的匯入方式,但沒有任何差別。

答案#1

作為一種暴力方法,我使用自訂的 typings 檔案來滿足 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"
         ]
    }
}