前端之React实战-快速入门以及集成使用

Quick Start

HelloWorld

基本的React的页面形式如下所示:

    <!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这个文件进行客户端的编译,不过还是推荐在服务端编译。

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映射表。

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

Setup:开发环境搭建

完整的React开发环境应该包括了JSX/ES6的解析以及模块化管理,笔者在这里是选用了WebPack与Babel。Webpack是一个强大的包管理以及编译工具,

参考资料

  • react-webpack-cookbook

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:项目结构

一个典型的项目结构你可以参考这个仓库

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是笔者喜欢的两个框架,二者可以相辅相成。可以查看笔者的这个库。

Integrated With jQuery

ES6

refactoring-react-components-to-es6-classes

ES6是一门非常让人兴奋的语言,而React自身的譬如JSX这样的语法也是别具特色,笔者一贯坚持从现在开始就广泛使用ES6。而在React的实践编程中,如果需要完全使用ES6语法进行开发,需要注意以下几点。

使用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这个库。

    原文作者:王下邀月熊_Chevalier
    原文地址: https://segmentfault.com/a/1190000003745823
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞