在package.json添加javascript
"dependencies": { "react": "^0.14.0", "react-dom": "^0.14.1" }
安裝依賴html
npm init
或者直接java
npm install react react-dom --save-dev
在你編寫的react組件文件裏 react
在你的入口文件裏 webpack
其餘事情就交給webpack去作吧。、web
這種方法更方便,可是不利用實際開發,平時練習也就算了。npm
<script src="build/react.js"></script> <script src="build/JSXTransformer.js"></script> <script src="build/browser.min.js"></script>
組件類的第一個字母必須大寫
JS代碼json
var Comment=React.createClass({ render:function(){ return ( <div className = "comment" > <h2 className="commentAuthor"> {this.props.author} </h2> <p className="commentContent">{this.props.children}</p> </div> ); } }) React.render( <Comment author="Liz"> Hello!world. </Comment>, document.getElementById('container') );
Html代碼dom
<div id="container"></div>
Resultui
若是不使用jsx語法,咱們還有兩種方法建立組件。
(1)Jsx,更加語義化,可直接套子節點和內容
<div className = "comment" > <h2 className="commentAuthor"> Liz </h2> <p className="commentContent">Hello!world.</p> </div>
(2)React,相似於json格式,須要什麼就嵌套,可是參數順序比較嚴格,參數一爲標籤名,第二個屬性json格式,第三個是內容,第二個不能省略,實在沒有屬性就填null.
React.createElement("div", {className:"comment"}, React.createElement("h2",{className:"commentAuthor"},"Liz"), React.createElement("p",{className:"commentContent"},"Hello!world.") )
(3)React工廠
var div = React.DOM.div; var h2 = React.DOM.h2; var p = React.DOM.p; div({className:"comment"}, h2({className:"commentAuthor"},"Liz"), p({className:"commentContent"},"Hello!world."))
獲得的結果都是同樣的。
相比之下,我仍是更傾向於Jsx寫法。