1. 程式人生 > >react-antd螞蟻金服組件實例

react-antd螞蟻金服組件實例

組成 router 文件配置 group XML icon tput pro ops

React框架已經火了好長一段時間了,再不學就out了!

對React還沒有了解的同學可以看看我之前的一篇文章,可以快速簡單的認識一下React。React入門最好的實例-TodoList

自己從開始接觸react一竅不通,到慢慢的似懂非懂,通過各種途徑學習也有一陣了。學習過程中還會接觸到很多新的東西,比如ES6、 webpack,過程艱辛誰人懂,見坑填坑慢慢來。今天把學習過程過濾了一下,只說項目實際需要用的東西,總結了一套能看到的東西,分享給大家,希望能讓 讀者少踩一些坑!

本文看點

  • 實際項目效果:最終你只需要在本地啟一個服務,就能看到運行效果。
  • webpack的配置:項目實戰中常用的插件和配置方法。
  • React用法:React在MVC(模型Model-視圖View-控制器Controller)層面上主要扮演了視圖的作用。我們可以學習它在項目中到底該如何使用。
  • React-router配置:單頁面應用(SPA)離不開路由,我們可以學習在項目中React-router如何配置。
  • ES6語法:我們會用到一些在項目中常見的ES6語法。
  • antd的使用:螞蟻金服出的一款基於React的框架,我們可以學習如何去使用。

項目效果

項目代碼已經上傳至github,項目代碼github地址。大家把代碼下載下來之後,跟隨以下步驟即可在本地看到效果。

  • 首先安裝node環境。

  • 全局安裝webpack

    npm install webpack -g  
  • 安裝項目依賴

    npm install
  • 開發模式,啟動本地服務

    npm run dev

    至這一步成功後,在瀏覽器輸入localhost:8888就能看到如下圖的效果了。

    技術分享圖片

  • 在build文件夾下打包

    npm run build

webpack配置

基於React的項目配合webpack來打包管理最合適不過了。但是不學不知道,一學嚇一跳,webpack的學習TM復雜了,各種報錯,各種坑,就是webpack讓我在學習的過程中一度想要放棄。然而過來人告訴你,堅持就是勝利!

學會怎麽配置webpack,是獨立管理項目的第一步。每個用webpack管理的項目都有一個webpack.config.js

文件,先來看看這個項目的webpack.config.js文件:

‘use strict‘;
var ExtractTextPlugin = require("extract-text-webpack-plugin");  //css單獨打包
var CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");
module.exports = {
    devtool: ‘eval-source-map‘,
    entry: {
        main: ‘./src/entry.js‘, //唯一入口文件
        vendor: [‘react‘]   //這裏是依賴的庫文件配置,和CommonsChunkPlugin配合使用可以單獨打包
    },
    output: {
        path: ‘./build‘, //打包後的文件存放的地方
        filename: ‘main.js‘, //打包後輸出文件的文件名
        publicPath: ‘http://localhost:8888/build/‘  //啟動本地服務後的根目錄
    },
    module: {
        loaders: [
            { test: /\.js$/, loader: "jsx!babel", include: /src/},
            { test: /\.css$/, loader: ExtractTextPlugin.extract("style", "css!postcss")},
            { test: /\.scss$/, loader: ExtractTextPlugin.extract("style", "css!postcss!sass")},
            { test: /\.(png|jpg|gif)$/, loader: ‘url?limit=819200‘}
        ]
    },
    babel: {
        presets: [‘es2015‘, ‘stage-0‘, ‘react‘],
        plugins: [‘transform-runtime‘, [‘import‘, {
          libraryName: ‘antd‘,
          style: ‘css‘
        }]]
    },
    postcss: [
        require(‘autoprefixer‘)    //調用autoprefixer插件,css3自動補全
    ],
    devServer: {
        // contentBase: ‘./src/views‘  //本地服務器所加載的頁面所在的目錄
        port: 8888,
        colors: true,  //終端中輸出結果為彩色
        historyApiFallback: true,  //不跳轉
        inline: true  //實時刷新
    },
    plugins: [
        new ExtractTextPlugin(‘main.css‘),
        new CommonsChunkPlugin({
           name: ‘vendor‘,
           filename: ‘vendor.js‘
        })
    ]
}

一個完整項目的基本webpack配置就是這些了,重要的配置項已經在上述代碼中作了註釋。另外,也可以深入學習,推薦看看這篇文章。webpack詳細指南

React用法

React本身真的非常簡單。你可以把一個頁面分為很多個組件的組成,而React就是開發這些組件的。所以React其實就是view層,說白了就是html,只不過每個組件是通過js創建的,每個組件還有自己的狀態和自己的方法。

React Component(一個組件)提供一個render方法以及其他可選的生命周期函數、組件相關的事件或方法定義。常用API就以下幾個:

  • constructor:構造函數

    class component extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                color: props.initialColor
            };
        }
    }
  • render:組件返回的dom內容(必須)

  • componentWillMount:在render之前自動調用,你可以在這個方法裏面調用setState改變狀態,並且不會導致額外調用一次render

  • componentDidMount:在render之後自動調用,從這裏開始可以通過this.getDOMNode()獲取到組件的DOM節點

  • componentWillUpdate: 組件收到新的state,更新view之前自動調用

  • componentDidUpdate: 組件收到新的state,更新view完成之後自動調用

然後回到我們這個項目實例,拿代碼中的進度條組件(src-components-progress.js)代碼作為展示:

import React from ‘react‘;    //引入react
import { Progress, Button } from ‘antd‘;    //引入antd
const ButtonGroup = Button.Group;
class myProgress extends React.Component {
    constructor(props) {
        super(props)
        this.state = {   //初始化組件的狀態
            percent: 0
        }
    } 
    increase() {   //自定義函數
        let percent = this.state.percent + 10;
        if (percent > 100) {
            percent = 100;
        }
        this.setState({ percent });   //設置組件的狀態
    }
    decline() {   //自定義函數
        let percent = this.state.percent - 10;
        if (percent < 0) {
            percent = 0;
        }
        this.setState({ percent });
    }
    render() {
        return (
            <div className="progress-wrap">    //類名使用className
                <Progress percent={this.state.percent} />
                <Progress type="circle" percent={this.state.percent} />
                <ButtonGroup>
                    <Button type="ghost" onClick={this.decline.bind(this)} icon="minus" />
                    <Button type="ghost" onClick={this.increase.bind(this)} icon="plus" />
                </ButtonGroup>
                <span>點擊按鈕可以看到進度條的變化</span>
            </div>
        )
    }
}
export default myProgress;  //導出這個組件(ES6語法)

代碼我已經給出了註釋,不做贅述。

React-router配置

獨立的前端應用離不開路由配置,就像angular框架也有自己的路由一樣。在React項目中使用路由,需要依賴React-Router模塊。我們直接來看看此項目中的路由配置:

import ReactDom from ‘react-dom‘;
import { Router, Route, Link, hashHistory, IndexRoute, Redirect, IndexLink} from ‘react-router‘;
ReactDom.render((
    <Router history={hashHistory}>   //路由容器
        <Route path="/" component={Sider}>    //一級路由,路徑為"/"時,加載“Sider”組件
            <IndexRoute component={myIntroduce} />   //默認路由,加載“Sider”和“myIntroduce”組件
            <Route path="myIntroduce" component={myIntroduce} />   //二級路由
            <Route path="myTable" component={myTable} />    //二級路由
            <Route path="myForm" component={myForm} />   //二級路由
            <Route path="myProgress" component={myProgress} />   //二級路由
            <Route path="myCarousel" component={myCarousel} />   //二級路由
        </Route>
    </Router>
), document.getElementById(‘app‘));

React的路由配置其實很簡單,就是把路徑和定義好的組件一一對應起來就好了。上述代碼結合實際運行效果,一看就明白。

ES6語法

我之前寫過一篇關於ES6常見語法的文章,總結ES6常用的新特性。

另外,上述貼出的代碼中已經出現過很多的ES6語法。ES6的學習就是見多學多的過程,多使用,多總結,自然就會了。

antd的使用

antd可以理解為是一個基於react的ui組件庫。引入這個庫之後,我們就可以直接使用很多現成的組件,比如按鈕、圖標、表單、菜單、導航等等。去antd官網發現更多牛逼的組件。

比如上面已經貼過的進度條組件:

import { Progress, Button } from ‘antd‘;    //引入antd
const ButtonGroup = Button.Group;   //按鈕組
......
<Progress percent={this.state.percent} />    //使用進度條組件,percent是組件提供的配置項
<Progress type="circle" percent={this.state.percent} />
<ButtonGroup>
    <Button type="ghost" onClick={this.decline.bind(this)} icon="minus" />
    <Button type="ghost" onClick={this.increase.bind(this)} icon="plus" />
</ButtonGroup>
......

另外,由於antd組件比較多,所以庫文件比較大,所以我們在開發的時候可以按需引入對應的庫。webpack配置需要用到babel-plugin-import模塊。

babel: {
    presets: [‘es2015‘, ‘stage-0‘, ‘react‘],
    plugins: [‘transform-runtime‘, [‘import‘, {
        libraryName: ‘antd‘,
        style: ‘css‘
    }]]
}

總結

上面的項目我已放到了Github上。基於react+antd的項目實例,喜歡的看管麻煩star一下啦!謝謝~

學習的過程枯燥艱辛,但是取得的成果卻令人興奮。所以我們還是要不忘初心,不忘學習!

react-antd螞蟻金服組件實例