javascript - ReactJS 中的导出(默认)类

标签 javascript syntax reactjs ecmascript-6

如果我正在创建一个组件,您似乎可以通过多种不同的方式创建一个类。这些有什么区别?我怎么知道要使用哪一个?

import React, {Component} from 'react'

export default class Header extends Component {

}

export const Header = React.createClass({

})

export default React.createClass({

})

我只是假设它们做不同的事情,还是只是语法不同?

如果有人能给我一个快速的解释或链接,我将不胜感激。我不想从不知 Prop 体区别的新框架开始。

最佳答案

您好,欢迎来到 React!

我认为您在这里遇到的部分问题并不是真正特定于 React,而是与新的 ES2015 模块语法有关。在创建 React 类组件时,对于大多数意图和目的,您可以将 React.createClass 视为在功能上等同于 class MyComponent extends React.Component。一种只使用新的 ES2015 类语法,而另一种使用 ES2015 之前的语法。

要了解模块,我建议阅读一些关于新模块语法的文章以熟悉它。这是一个很好的开始:http://www.2ality.com/2014/09/es6-modules-final.html .

简而言之,这些只是语法上的差异,但我会尝试快速浏览一下:

/**
 * This is how you import stuff.  In this case you're actually 
 * importing two things:  React itself and just the "Component" 
 * part from React.  Importing the "Component" part by itself makes it
 * so that you can do something like:
 *
 * class MyComponent extends Component ...
 * 
 * instead of...
 * 
 * class MyComponent extends React.Component
 * 
 * Also note the comma below
 */
import React, {Component} from 'react';


/**
 * This is a "default" export.  That means when you import 
 * this module you can do so without needing a specific module
 * name or brackets, e.g.
 * 
 * import Header from './header';
 *
 * instead of...
 *
 * import { Header } from './header';
 */
export default class Header extends Component {

}

/**
 * This is a named export.  That means you must explicitly
 * import "Header" when importing this module, e.g.
 *
 * import { Header } from './header';
 *
 * instead of...
 * 
 * import Header from './header';
 */
export const Header = React.createClass({

})

/**
 * This is another "default" export, only just with a 
 * little more shorthand syntax.  It'd be functionally 
 * equivalent to doing:
 *
 * const MyClass = React.createClass({ ... });
 * export default MyClass;
 */
export default React.createClass({

})

关于javascript - ReactJS 中的导出(默认)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34840708/

相关文章:

javascript - 如何获取手机的位置

syntax - 在 Makefile 中以等号结束 `define` 之间的区别?

javascript - jQuery 包装全部 : preserving hierarchy of DOM elements

javascript - 如何在 Meteor/JavaScript 客户端中运行解锁后台任务?

javascript - 在 Rails 中的 javascript 中添加大块 HTML 的更简洁方法

javascript - JQuery 在链接前面添加文本

java - FileInputStream 在另一个类中?

reactjs - 如何内存自定义 React 钩子(Hook)

reactjs - 在 React 中集成 Metamask 中的 web3

reactjs - 如何调度 SyntheticEvent 事件?