我正在处理一个使用 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 element type 'MyComponent' is not a constructor function for JSX elements. Type 'MyComponent' is missing the following properties from type 'ElementClass': context, setState, forceUpdate, props, and 2 more.ts(2605) JSX element class does not support attributes because it does not have a 'props' property.ts(2607)

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

我知道 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" 
  ] 
} 

所以我希望它能起作用......

感谢您的帮助

请您参考如下方法:

您应该将 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" 
  ] 
} 

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

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


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!