简体   繁体   English

使用Typescript时无法从单独的文件导入React JSX

[英]Cannot import React JSX from separate file while using Typescript

The issue is similar to How to properly import React JSX from separate file in Typescript 1.6 . 问题类似于如何从Typescript 1.6中的单独文件中正确导入React JSX

It works fine when all the code is in a single file. 当所有代码都在一个文件中时,它工作正常。 But when I put the component to a different file and try to import, typescript compiler gives error. 但是当我将组件放到不同的文件并尝试导入时,typescript编译器会给出错误。

The code looks fine. 代码看起来很好。

Error I get is 我得到的错误是

JSX element type 'Hello' does not have any construct or call signatures. JSX元素类型“Hello”没有任何构造或调用签名。

app.tsx app.tsx

/// <reference path="typings/tsd.d.ts" />
import React = require('react');
import ReactDOM = require('react-dom');
import $ = require('jquery');
import Hello = require('./components/Hello');

$(()=>{
    ReactDOM.render(<Hello name="Tom" />,document.body);
});

components/Hello.tsx 组件/ Hello.tsx

/// <reference path="../typings/tsd.d.ts" />
import React = require('react');

export default class Hello extends React.Component<any,any>{
    render(){
        return <div className="hello">Hello {this.props.name} !</div>;
    }
}

tsconfig.json tsconfig.json

{
    "compilerOptions": {
        "module": "commonjs",
        "jsx": "react"
    }
}

If you wrote these lines 如果你写了这些行

export default class Hello ...
/* and */    
import Hello = require('./components/Hello');

Then you need to write this to consume it: 然后你需要写这个来消耗它:

<Hello.Hello name="Tom" />

You could instead write this, to change the module to export the class as its top-level object: 您可以改为编写此代码,以更改模块以将类导出为其顶级对象:

class Hello ...
export = Hello

or you could import the Hello export from the module with a destructuring: 或者您可以通过解构从模块导入Hello导出:

import { Hello } from './components/Hello';

or you could import the default export from the module: 或者您可以从模块导入默认导出:

import Hello from './components/Hello';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM