React全家桶打造共享單車后台管理系統項目_第1篇_項目環境搭建_首頁編寫


1.項目介紹

項目github地址:https://github.com/replaceroot/React-manageSystem

 項目整體架構:

 

課程大綱:
    第一章:React基礎知識
    第二章:主頁面架構設計
    第三章:Router4.0 路由實戰演練
    第四-六章:常用UI組件
    第七、八章:單車業務基本功能開發
    第九章:項目工程化開發
    第十到十三章:單車業務核心模塊開發
    第十四章:Redux集成
 

 

 

 

補充:調用setState之后會並列調用should update,will update,did update生命周期函數

Babel插件的作用:解析E6達到兼容效果

 

2.項目環境搭建

2.1 安裝包

yarn add react-router-dom axios --dev

 

2.2 安裝支付寶UI組件

yarn add antd

 

2.3 配置antd組件按需加載

yarn add react-app-rewired customize-cra

修改`package.json`配置文件的`scripts`字段

  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject"
  }

 然后在項目根目錄創建一個 config-overrides.js 用於修改默認配置。

module.exports = function override(config, env) {
  // do stuff with the webpack config...
  return config;
};

使用 babel-plugin-import

 babel-plugin-import 是一個用於按需加載組件代碼和樣式的 babel 插件(原理),現在我們嘗試安裝它並修改 config-overrides.js 文件。

yarn add babel-plugin-import
+ const { override, fixBabelImports } = require('customize-cra');

- module.exports = function override(config, env) {
-   // do stuff with the webpack config...
-   return config;
- };
+ module.exports = override(
+   fixBabelImports('import', {
+     libraryName: 'antd',
+     libraryDirectory: 'es',
+     style: 'css',
+   }),
+ );

 

記錄一個小坑:

如果遇到錯誤,將 react-scripts添加到dev依賴中。

  yarn add react-scripts --dev

 

如果遇到找不到babel模塊的錯誤,就將整個 modules刪除,然后重新yarn install安裝一下就能解決。

重新運行項目,此時就能正常顯示Button按鈕了。

import React from "react";
import Child from "./Child";
import { Button } from 'antd';
import "./index.less";

export default class Life extends React.Component {
  state = {
    count: 0
  };

  handleAdd = () => {
    this.setState({
      count: this.state.count + 1
    });
  };

  render(){
    return (
      <div className="demo">
        <input type="text" placeholder="請輸入內容..."/>
        <Button onClick={this.handleAdd}>點擊一下</Button>
        <p>{this.state.count}</p>
        {/* 給子組件傳參 */}
        <Child name={this.state.count}></Child>
      </div>
    )
  }
}

 

 

但是有一個問題,就是我們配置的less沒有生效,下面解決Less和按鈕主題顏色問題。

yarn add less less-loader

按照 配置主題 的要求,自定義主題需要用到 less 變量覆蓋功能。我們可以引入 customize-cra 中提供的 less 相關的函數 addLessLoader 來幫助加載 less 樣式,同時修改 config-overrides.js 文件如下。

- const { override, fixBabelImports } = require('customize-cra');
+ const { override, fixBabelImports, addLessLoader } = require('customize-cra');

module.exports = override(
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
-   style: 'css',
+   style: true,
  }),
+ addLessLoader({
+   javascriptEnabled: true,
+   modifyVars: { '@primary-color': '#1DA57A' },
+ }),
);

修改后重啟 yarn start,如果看到一個綠色的按鈕就說明配置成功了。

 

到這里, 基本的環境算是搭建好了,坑是真的多,也只能自己摸索,百度、Google查文檔,做記錄總結。

 

 

3.項目主頁面編寫

3.1 目錄結構

 

具體代碼參考我的github的commit代碼

布局使用的柵格系統:https://ant.design/components/grid-cn/

 

左側菜單渲染:https://ant.design/components/menu-cn/

 

具體實現可以參考我github上的源碼和官網給出的demo的源碼進行對比就知道我如何使用的。

 

3.2左側菜單動態渲染

重點就是動態渲染的代碼

import React from "react";
import { Menu, Icon, Divider } from "antd";
import menuConfig from "../../config/menuConfig";
import "./index.less";
const { SubMenu } = Menu;

export default class NavLeft extends React.Component {
  // 加載時的生命周期函數
  componentWillMount() {
    const menuTreeNode = this.renderMenu(menuConfig);
    this.setState({
      menuTreeNode
    });
  }

  // 菜單動態渲染
  renderMenu = data => {
    return data.map(item=>{
        // 如果item中還有子項,那么就把子項遞歸遍歷渲染到頁面
      if(item.children){
        return (
          <SubMenu title={item.title} key={item.key}>
            {this.renderMenu(item.children)}
          </SubMenu>
        );
      }
      return <Menu.Item title={item.title} key={item.key}>{item.title}</Menu.Item>
    })
  };

  render() {
    return (
      <div>
        <div className="logo">
          <img src="assets/logo-ant.svg" alt="" />
          <h1>木子單車管理系統</h1>
        </div>
        <Menu theme="dark">{this.state.menuTreeNode}</Menu>
      </div>
    );
  }
}
index.js

 

 

3.3 header頭部頁面實現

這個部分需要發送跨域請求百度天氣的API來獲取數據渲染,需要安裝一個JsonP。

yarn add jsonp

這里部分需要使用jsonp封裝一個axios來發送跨域請求,這里涉及了jsonp使用和ES6中promise的使用方法,如果忘記了這些技術,趕緊翻下以前的筆記,百度看下博客吧。

簡單的jsonp demo

getjsonp(){
    // jsonp能發起跨域請求
    this.$http.jsonp('http://127.0.0.1:3003/getlist')
        .then((res) => {
        console.log(res)
    },(err) => {
        console.log(err)
    })
}

 

// 封裝axios發送跨域請求
import JsonP from 'jsonp'
export default class Axios {
  /* 這里使用static關鍵字聲明了一個靜態方法,實例不能直接調用,只能通過類來調用 */
  static jsonp(options){
    // 成功就是resolve,失敗就是reject
    return new Promise((resolve, reject)=>{
      JsonP(options.url, {
        params: 'callback'
      }, function(err, response){
        if(response.status === 'success'){
          resolve(response)
        }else {
          reject(response.message);
        }
      })
    })
  }
}
給axios封裝jsonp方法

 

/* 封裝一個格式化時間戳的方法 */

export default {
  formateDate(time) {
    // 如果為空就返回空字符串
    if (!time) return "";
    let date = new Date(time);
    return (
      date.getFullYear() +
      "-" +
      (date.getMonth() + 1) +
      "-" +
      date.getDate() +
      " " +
      date.getHours() +
      ":" +
      date.getMinutes() +
      ":" +
      date.getSeconds()
    );
  }
};
封裝格式化日期方法

 

 

3.4 Footer頁面以及content內容區域實現

增加小箭頭樣式

/* 實現小箭頭 */
      &:after{
        position: absolute;
        content: '';
        left: 110px;
        top:39px;
        border-top: 9px solid @colorM;
        border-left: 12px solid transparent;
        border-right: 12px solid transparent;

       }
Header/index.less

 

 

到此為止首頁就編寫完成了,以后會根據課程的目錄來更新React路由相關的知識,其他業務功能的實現。

總結一下:很多都是基礎知識,稍微難一點的就是Promise、jsonp、還有初期的環境搭建遇到的幾個坑,幾乎沒有太難的知識點,結構和flex布局相關的內容就是一個熟練度的問題,代碼量上去了,看到一個效果就知道要怎么實現,多敲多練多思考就完事了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM