在 TypeScript 中使用 JS React 组件:JSX 元素类型“MyComponent”不是 JSX 元素的构造函数

新手上路,请多包涵

我正在处理一个使用 React 框架的 JavaScript 遗留项目。我们定义了一些 React 组件,我想在一个完全不同的 TypeScript React 项目中重新使用它们。

JS React 组件在 controls.jsx 文件中定义,如下所示:

 export class MyComponent extends React.Component {
  render() {
    return <h1>Hi from MyComponent! Message provided: {this.props.message}</h1>;
  }
}

在我的 TypeScript React 项目中,我试图这样使用它:

 import * as React from "react";
import * as ReactDOM from "react-dom";
import { MyComponent } from "../JavaScriptProject/controls";

ReactDOM.render(
  <MyComponent message="some nice message"/>,
    document.getElementById("documents-tree")
);

但我收到以下错误: 在此处输入图像描述

错误消息说:

JSX 元素类型“MyComponent”不是 JSX 元素的构造函数。类型“MyComponent”缺少类型“ElementClass”中的以下属性:context、setState、forceUpdate、props 和 2 more.ts(2605) JSX 元素类不支持属性,因为它没有“props”property.ts (2607)

我已经尝试过 这个 问题中描述的自定义类型文件的解决方案,但它没有任何改变。

我知道 JS 组件缺少 TypeScript 所需的一些强类型属性,但在我的 tsconfig.json 中我将 allowJs 设置为 true

 {
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "experimentalDecorators": true,
    "jsx": "react",
    "noEmitOnError": true,
    "outDir": "lib",
    "sourceMap": true,
    "target": "es5",
    "lib": [
      "es2015",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "lib",
    "lib-amd"
  ]
}

所以我希望它能奏效……

谢谢你的帮助

原文由 Dawid Sibiński 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 844
1 个回答

您应该将 allowSyntheticDefaultImports 转换为 true 因为 React 不会导出默认值。

(来源: https ://github.com/facebook/react/blob/master/packages/react/index.js)

 {
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true, // turn on allowSyntheticDefaultImports
    "jsx": "react",
    "noEmitOnError": true,
    "outDir": "lib",
    "sourceMap": true,
    "target": "es5",
    "lib": [
      "es2015",
      "dom"
    ]
  },
  "exclude": [
    "node_modules",
    "dist",
    "lib",
    "lib-amd"
  ]
}

此外,您应该为组件道具添加形状。例如,在您的代码中:

 export class MyComponent extends React.Component<{ message: string }> { ...

原文由 Long Nguyen Duc 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题