如何在Typescript模块(.tsx)中导入JSX中定义的现有React组件

问题描述 投票:2回答:3

我有一个在JSX中编码的现有React组件,此时我无法转换为Typescript。我想在一个用Typescript编写的新React应用程序中使用它。我无法弄清楚是否可以在TSX代码中导入和使用JSX代码。这可能吗?我该怎么做?

谢谢

下面的示例给出了错误:TS2604:JSX element type 'OldCode' does not have any construct or call signatures.

OldCode.jsx

import React from 'react'

export default React.createClass({
  render() {
    return <div>OldCode</div>
  }
})

NewCode.tsx

import * as React from 'react';
import { OldCode } from './OldCode';

export default class NewCode extends React.Component<any, any> {
  render() {
    return (
      <OldCode/>
    );
  }
}
reactjs typescript jsx tsc
3个回答
0
投票

尝试更改import语句:

import OldCode from './OldCode';

如果您使用的是webpack,则可能需要将.jsx添加到解析器中。


0
投票
declare module '*.jsx' {
    var _: React.Component<any, any>;
    export default _;
}

并使用它

import OldCode from './OldCode.jsx';

把它放在一些文件中,确保它包含在tsconfig.json中。

当然,请确保webpack将它们全部打包。


0
投票

由于没有可接受的答案,我将链接到我的问题,实际上回答如何为现有组件编写定义文件(我的问题是关于包含在redux连接中的组件):

[How do I create a typescript definition file (d.ts) for an existing redux connected (jsx)component?

希望它可以帮助某人......

© www.soinside.com 2019 - 2024. All rights reserved.