如何从 Typescript 1.6 中的单独文件正确导入 React JSX

How to properly import React JSX from separate file in Typescript 1.6

我有以下 app.tsx 文件工作正常加载来自 React.Component 的 App 元素和来自另一个 React.Component 的子 Worklist 元素(两者都在 class 中定义相同的 app.tsx 文件)。这是 Visual Studio 中的 运行,安装了 Typescript 1.6(ECMAScript 版本:ECMAScript 5,JSX 编译:React,模块系统:CommonJS)。

不过,我想将这两个组件拆分成单独的文件。但是,当我取消注释 WorkList 的导入并从 app.tsx 中删除 WorkList 组件的 class 定义时 - 它失败并出现错误:

Error TS2604 JSX element type 'WorkList' does not have any construct or call signatures.

这是有效的 app.tsx 和所需的 worklist.tsx。

// app.tsx
import * as React from "react";
import * as ReactDOM  from "react-dom";
//import * as WorkList from "./worklist";

interface Props {
    foo: string;
}

class WorkList extends React.Component<Props, {}> {
    constructor(props: Props) {
        super(props);
    }
    render() {
        return <h2>WorkList!{this.props.foo} </h2>
    }
}
class App extends React.Component<Props, {}> {
    constructor(props: Props) {
        super(props);
    }
    public render() {
        return <WorkList foo="baz"></WorkList>
    }
}


ReactDOM.render(    
    React.createElement(App, { foo: 'bar' }),
    document.getElementById('app')
);




//worklist.tsx
import * as React from "react";

interface Props {
    foo: string;
}

class WorkList extends React.Component<Props, {}> {
    constructor(props: Props) {
        super(props);
    }
    render() {
        return <h2>WorkList!{this.props.foo} </h2>
    }
}

<WorkList foo="bar" />

使用 Typescript 1.6 导入子 JSX 的正确方法是什么?

这是应用了正确答案的工作代码:

// app.tsx
import * as React from "react";
import * as ReactDOM  from "react-dom";
import WorkList from "./worklist";

interface Props {
    foo: string;
}

class App extends React.Component<Props, {}> {
    constructor(props: Props) {
        super(props);
    }
    public render() {
        return <WorkList foo="baz"></WorkList>
    }
}       
ReactDOM.render(

    React.createElement(App, { foo: 'bar' }),
    document.getElementById('app')
);

//worklist.tsx
import * as React from "react";

interface Props {
    foo: string;
}

export default class WorkList extends React.Component<Props, {}> {
    constructor(props: Props) {
        super(props);
    }
    render() {
        return <h2>WorkList!{this.props.foo} </h2>
    }
}

我希望您需要在 worklist.tsx 文件中正确导出 WorkList class,例如作为默认导出:

export default class WorkList extend React.Component<Props, {}>

然后导入到app.tsx:

import WorkList from "worklist"

这应该可以解决您的问题。