简体   繁体   English

如何在es6中编写子组件(子组件)?

[英]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. 我正在尝试将我的react应用程序从es5重构为es6,但是在渲染功能中,我保留了我和我的组件,当我重构为ES6时,这些组件未显示在我的页面中。 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 像这样默认导出您的Header和Footer类

export default class Footer

Or import it this way: 或以这种方式导入:

import {Footer} from '../pathToFile'

So there are two ways to export in ES6. 因此,在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. 您需要使用导出时提到的相同名称导入它。

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

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