简体   繁体   中英

How to write sub-component (child components) in es6?

I am trying to refactor my react app from es5 to es6, however in render function I've kept my and components, when I refactor to ES6 these components are not displayed in my page. Searched in google but couldn't get the proper solution, below is my code

 'use strict'; import React from 'react'; import { Router, Route, Link, hashHistory } from 'react-router'; import Header from '../Header/header'; import Footer from '../Footer/footer'; export class Main extends React.Component { render(){ return ( <div> <Header /> <div> {this.props.children} </div> <Footer /> </div> ); } } 

below is my Footer:

 'use strict'; import React from 'react'; export class Footer extends React.Component { render(){ return ( <div> <footer> <div className="panel panel-default"> <div className="panel-footer container"> &copy; {year} All rights reserved </div> </div> </footer> </div> ); } } 

Header and Footer components are not being rendered.

Either export your Header and Footer classes with default like this

export default class Footer

Or import it this way:

import {Footer} from '../pathToFile'

So there are two ways to export in ES6. The first one is a default export which is written like this:

export default someVariable

If you export a variable this way, the you can import it in any other file this way:

import someVariable from '<path>'

The catch here is that you can even import your variable with a different name. Hence,

import someVariable2 from '<path>'

will also give me someVariable. But there is a restriction as well. You can have only one export default in a single file

Now the other way of exporting is the Named Export like this:

export somevariable

In this case, you need to import it this way:

import {someVariable} from '<path>'

In this case, the variable name ca't be changed. You need to import it with the same name which you mentioned while exporting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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