javascript 为什么我的 React 组件导出不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47619405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:30:30  来源:igfitidea点击:

Why does my React Component Export not work?

javascriptreactjswebpackwebpack-dev-server

提问by gerdtf

I was just getting into react and trying it out for myself. After hours of configuring webpack just to get a hello world on my screen I thought I could get going now but after trying to render another component from a file the next problem.

我刚刚开始反应并为自己尝试。经过几个小时的配置 webpack 只是为了在我的屏幕上显示一个 hello world,我以为我现在可以开始了,但是在尝试从文件渲染另一个组件之后,下一个问题出现了。

My main file is app.js, which renders everything:

我的主文件是 app.js,它呈现所有内容:

import React from 'react';
import ReactDOM from 'react-dom';
import {Hello} from './hello';

ReactDOM.render(
   <Hello/>,
   document.getElementById('app')
);

The Hello component comes from my hello.js in the same folder:

Hello 组件来自同一个文件夹中的 hello.js:

import React from 'react';

class Hello extends React.Component{
   render(){
       return (
           <h1>Hello, world!</h1>
       )
    }
}

export default Hello;

It was rendering fine when I was doing everything just in app.js without the import/export. It also compiles fine. But there are a lot of errors now in the console. So what am I missing?

当我在没有导入/导出的情况下在 app.js 中做所有事情时,它渲染得很好。它也编译得很好。但是现在控制台中有很多错误。那么我错过了什么?

Thanks

谢谢

Gerd

格尔德

回答by Andy

Because your export is defaultyou don't need braces around your import component name:

因为您的导出是default您不需要在导入组件名称周围使用大括号:

import Hello from './hello';

Here's a verbose technical articlefrom Axel Rauschmayer on the final ES6 modules syntax that you might find useful.

这是Axel Rauschmayer 关于最终 ES6 模块语法的详细技术文章,您可能会觉得有用。

And here's a slightly less techy postabout the same topic.

这是关于同一主题的技术性稍差的帖子

回答by mina sameh

when you import the default class you use

当您导入您使用的默认类时

import ClassName from 'something';

and when you import other classes you use

当你导入你使用的其他类时

import {ClassName} from 'something';

an example:

一个例子:

in hello.js file

在 hello.js 文件中

import React from 'react';

class Hello extends React.Component{
   render(){
       return (
           <h1>Hello, world!</h1>
       )
    }
}

class Other extends React.Component{
   render(){
       return (
           <h1>Hello, world!</h1>
       )
    }
}
export default Hello;
export Other;

in other file

在其他文件中

import Hello, {Other} from './hello';

tip: you could also import the default class with other name

提示:您也可以使用其他名称导入默认类

import Component, {Other} from './hello';