首先,React肯定是跑在服务器端,要求用到es6语法。

一、装nvm

git clone https://github.com/creationix/nvm.git ~/.nvm  
export NVM_DIR="$HOME/.nvm"  
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"

二、装npm和node

nvm ls-remote  
nvm install v7.10.1  

三、初始化一个项目,生成的package.json,保留三行主要内容,无关的可以删除掉

mkdir project1  
cd project1  
npm init  
...
  "name": "my-tutorial-react",
  "version": "0.0.1",
  "description": "my tutorial slim and react",
...

四、装各种库,babel是转换es6到es2015用的,浏览器还没有都支持到es6那么先进,所以要编译到es2015来普适浏览器。webpack是打包工具,来完成这些转换工作.

npm i --save react react-dom babel-core babel-loader webpack babel-preset-es2015 babel-preset-react  

五、配置webpack

vi webpack.config.js

var path = require('path');

module.exports = {  
    entry: './app/js/app.jsx',
    output: {
        path: __dirname,
        filename: './static/build.js'
    },
    module: {
        loaders: [
            {
                test: /.jsx?$/,
                loader: 'babel-loader',
                exclude: /(node_modules)/,
                query: {
                   presets: ['es2015', 'react'] 
                }
            }
        ]
    }
};

六、准备个html文件

<!DOCTYPE html>  
<html>  
<head>  
    <meta charset="UTF-8"/>
    <title>TEST</title>
</head>  
<body>

<div id="app"></div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
<script src="./static/build.js" ></script>  
</body>  
</html>  

七、撰写jsx

mkdir app/js  
vi app/js/app.jsx

import React from 'react'  
import ReactDOM from 'react-dom'

class App extends React.Component {  
    constructor(props) {
        super(props);
        this.state = {
             users: []
        }
    }

    componentDidMount() {
        $.ajax({
            url: '/dapan/slim/index.php',
            type: 'GET',
            dataType: 'json',
            cache: 'false',
            success: function (res) {
                this.setState({ users: res });
            }.bind(this),
            error: function (xhr, status, err) {
                console.log(status, err.toString());
            }.bind(this)
        })
    }

    render() {
        return (
            <ul>
            {
                this.state.users.map(result=>{
                    return (
                        <li key={result.user_id}>
                            {result.username}
                        </li>
                    )
                })
            }
            </ul>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'))  

注意上面的例子,用到了es6特有的=>箭头函数

八、用webpack打包

./node_modules/webpack/bin/webpack.js

最后在浏览器打开对应的网址即可。

comments powered by Disqus