Why does my React Component Export not work?

℡╲_俬逩灬. 提交于 2020-02-23 09:01:32

问题


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.

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

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:

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?

Thanks

Gerd


回答1:


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

import Hello from './hello';

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

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




回答2:


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

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';


来源:https://stackoverflow.com/questions/47619405/why-does-my-react-component-export-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!