2016-01-17 14 views
30

コンポーネントを作成している場合は、さまざまな方法でクラスを作成できます。これらの違いは何ですか?どちらを使用するのかをどのように知るのですか?ReactJSのエクスポート(デフォルト)クラス

import react {Component} from 'react' 

export default class Header extends component { 

} 

export const Header = React.createClass({ 

}) 

export default React.createClass({ 

}) 

私はちょうど彼らが別のことをしていると仮定しているのですか?

誰かが私に簡単な説明やリンクを教えていただけたら、本当にありがとう。私は、違いが何であるかを正確に知らない新しい枠組みから始めたくない。

答えて

76

こんにちは、歓迎します!

あなたがここで問題を抱えているのは、実際にはリアクション固有のものではなく、新しいES2015モジュールの構文に関係していると思います。 Reactクラスコンポーネントを作成するときは、ほとんどの目的と目的のために、React.createClassは機能的にはclass MyComponent extends React.Componentと同等であると考えることができます。 1つは新しいES2015クラス構文を使用していますが、もう1つは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({ 

}) 
+0

グレート説明 - ありがとうございました!小さな提案:あなたは 'import react ...'を 'import React ...'に更新して、推奨された大文字でhttps://facebook.github.io/react/docs/jsx-in-depth.html – epan

+0

を呼んでもよいでしょう。完了! –

+0

これはモジュールに関する優れた記事です:https://hacks.mozilla.org/2015/08/es6-in-depth-modules/ – Clauds

関連する問題