前端之React實戰-快速入門以及集成使用

Quick Start

HelloWorld

基本的React的頁面形式以下所示:javascript

<!DOCTYPE html>
    <html>
      <head>
        <script src="../build/react.js"></script>
        <script src="../build/JSXTransformer.js"></script>
      </head>
      <body>
        <div id="example"></div>
        <script type="text/jsx">
          // ** Our code goes here! **
        </script>
      </body>
    </html>

React首創了一種JS、CSS和HTML混寫的JSX格式,能夠經過在頁面中引入JSXTransformer這個文件進行客戶端的編譯,不過仍是推薦在服務端編譯。html

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.render(
  <HelloMessage name="John" />,
  document.getElementById('container')
);

React.render 是 React 的最基本方法,用於將模板轉爲 HTML 語言,並插入指定的 DOM 節點。要注意的是,React的渲染函數並非簡單地把HTML元素複製到頁面上,而是維護了一張Virtual Dom映射表。java

class ExampleComponent extends React.Component {
 constructor() {
  super();
  this. _handleClick = this. _handleClick.bind(this);
  this.state = Store.getState();
 }
 // ...
}

Setup:開發環境搭建

完整的React開發環境應該包括了JSX/ES6的解析以及模塊化管理,筆者在這裏是選用了WebPack與Babel。Webpack是一個強大的包管理以及編譯工具,node

參考資料react

  • react-webpack-cookbookwebpack

Webpack

Webpack是一個很是強大依賴管理與打包工具,其基本的配置方式能夠以下:
var path = require('path');
var node_modules = path.resolve(__dirname, 'node_modules');
var pathToReact = path.resolve(node_modules, 'react/dist/react.min.js');

config = {
    entry: ['webpack/hot/dev-server', path.resolve(__dirname, 'app/main.js')],
    resolve: {
        alias: {
          'react': pathToReact
        }
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'bundle.js',
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loader: 'babel'
        }],
        noParse: [pathToReact]
    }    
};

module.exports = config;

Project Structure:項目結構

一個典型的項目結構你能夠參考這個倉庫git

config/  
    app.js
    webpack.js (js config over json -> flexible)
src/  
  app/ (the React app: runs on server and client too)
    components/
      __tests__ (Jest test folder)
      AppRoot.jsx
      Cart.jsx
      Item.jsx
    index.js (just to export app)
    app.js
  client/  (only browser: attach app to DOM)
    styles/
    scripts/
      client.js
    index.html
  server/
    index.js
    server.js
.gitignore
.jshintrc
package.json  
README.md

Integrated With Angular

Angular與React是筆者喜歡的兩個框架,兩者能夠相輔相成。能夠查看筆者的這個庫。es6

Integrated With jQuery

ES6

refactoring-react-components-to-es6-classesgithub

ES6是一門很是讓人興奮的語言,而React自身的譬如JSX這樣的語法也是別具特點,筆者一向堅持從如今開始就普遍使用ES6。而在React的實踐編程中,若是須要徹底使用ES6語法進行開發,須要注意如下幾點。web

使用Class代替createClass

  • Before

var ExampleComponent = React.createClass({
 render: function() { 
  return <div onClick={this._handleClick}>Hello, world.</div>;
 },
 _handleClick: function() {
  console.log(this);
 }
});
  • After,這裏要注意將類的方法綁定到當前對象,避免在方法內部this指針被覆蓋

class ExampleComponent extends React.Component {
 constructor() {
  super();
  this. _handleClick = this. _handleClick.bind(this);
 }
 render() { 
  return <div onClick={this._handleClick}>Hello, world.</div>;
 }
 _handleClick() {
  console.log(this); // this is an ExampleComponent
 }
}

在Constructor中初始化State

若是使用createClass方法建立一個Component組件,能夠自動調用它的getInitialState方法來獲取初始化的State對象,可是在ES6的Class中並不會如此自動調用,所以,要稍做修改。

  • Before

class ExampleComponent extends React.Component {
 getInitialState() {
  return Store.getState();
 }
 constructor() {
  super();
  this. _handleClick = this. _handleClick.bind(this);
 }
 // ...
}
  • After

class ExampleComponent extends React.Component {
 constructor() {
  super();
  this. _handleClick = this. _handleClick.bind(this);
  this.state = Store.getState();
 }
 // ...
}

Mixin

Mixin是React中很是好用的一個功能,可是ES6提倡的面向對象,即便用類繼承等方式來進行傳遞。若是須要在ES6中繼續使用Mixin,特別是大量現存的React Library中的Mixin功能,能夠有如下幾種方式:

  • 使用extends繼承,而後在對應方法中調用父類方法。

  • 參考react-mixin這個庫。

相關文章
相關標籤/搜索