• 安装React脚手架:

    1. npm install -g create-react-app
  • 创建项目:

    1. create-react-app app

    app:为该项目名称

    或者跳过以上两步直接使用:

    1. npx create-react-app app
  • 启动项目:
    1. cd app
      npm start

项目创建完成,目录如下:

  • 安装 Ant Design:API Docs

    1. npm install antd --save

    2. cnpm install antd --save
    1. cnpm i antd -S

    没有权限请使用 sudo

使用 babel-plugin-import(推荐)。

  1. 首先暴露配置文件:

    1. npm run eject

    NOTE: Create React App 2+ supports TypeScript, Sass, CSS Modules and more without ejecting: https://reactjs.org/blog/2018/10/01/create-react-app-v2.html

    该操作为永久性,不可逆的。

  2. 在 package.json 中配置 babel (需要安装 babel-plugin-import 
    Error: Cannot find module 'babel-plugin-import'
    需要安装 babel-plugin-import
    1. npm install babel-plugin-import --save-dev

    2. cnpm install babel-plugin-import --save-dev
    1. cnpm i babel-plugin-import -D

    babel 配置如下:

    1. "babel": {
    2. "presets": [
    3. "react-app"
    4. ],
    5. "plugins": [
    6. [
    7. "import",
    8. {
    9. "libraryName": "antd",
    10. "libraryDirectory": "es",
    11. "style": true
    12. }
    13. ]
    14. ]
    15. }

    使用 babel-plugin-import 的 style 配置来引入样式,需要将配置值从 'style': 'css' 改为 'style': true,这样会引入 less 文件。

  3. 配置 Ant Design 中文语言(默认文案是英文):配置文档

    在入口文件index.js中配置:
    1. import { ConfigProvider } from 'antd';
    2. import zh_CN from 'antd/lib/locale-provider/zh_CN';
    3. import moment from 'moment';
    4. import 'moment/locale/zh-cn';
    5.  
    6. moment.locale('zh-cn');

    语言列表请参照:Ant Design 国际化

    另外需要使用 ConfigProvider 组件把 根组件 包裹起来:

    1. <ConfigProvider locale={zhCN}>
    2. <App />
    3. </ConfigProvider>
  • 安装配置 less 预处理器 && 配置 Ant Design 主题:  配置文档

    1. npm install less less-loader --save-dev

      cnpm install less less-loader --save-dev
      cnpm i less less-loader -D

    在 config/webpack.config.js 中配置 less:

    1. {
    2. test: /\.less$/,
    3. use: [{
    4. loader: 'style-loader',
    5. }, {
    6. loader: 'css-loader', // translates CSS into CommonJS
    7. }, {
    8. loader: 'less-loader', // compiles Less to CSS
    9. options: {
    10. modifyVars: {
    11. 'primary-color': '#1DA57A',
    12. 'link-color': '#1DA57A',
    13. 'border-radius-base': '2px',
    14. // or
    15. 'hack': `true; @import "your-less-file-path.less";`, // Override with less file
    16. },
    17. javascriptEnabled: true,
    18. },
    19. }]
    20. }

    配置位置如下:

    Ant Design 官网给出的可配置项:

    1. @primary-color: #1890ff; // 全局主色
    2. @link-color: #1890ff; // 链接色
    3. @success-color: #52c41a; // 成功色
    4. @warning-color: #faad14; // 警告色
    5. @error-color: #f5222d; // 错误色
    6. @font-size-base: 14px; // 主字号
    7. @heading-color: rgba(, , , 0.85); // 标题色
    8. @text-color: rgba(, , , 0.65); // 主文本色
    9. @text-color-secondary : rgba(, , , .); // 次文本色
    10. @disabled-color : rgba(, , , .); // 失效色
    11. @border-radius-base: 4px; // 组件/浮层圆角
    12. @border-color-base: #d9d9d9; // 边框色
    13. @box-shadow-base: 2px 8px rgba(, , , 0.15); // 浮层阴影
  • 安装 CSS resets: Normalize.css ( 样式重置 )
    1. npm install normalize.css --save

      cnpm install normalize.css --save
      cnpm i normalize.css -S

    安装完成后在入口文件index.js中引入即可。

    1. import 'normalize.css';
  • 安装配置 axios、qs : 
    1. npm install axios qs --save

      cnpm install axios qs --save
      cnpm i axios qs -S

    配置请求拦截器、响应拦截器:
     service.js:

    1. import axios from 'axios';
    2.  
    3. const service = axios.create({
    4. // baseURL: window.location.origin,
    5. timeout: ,
    6. /*headers: {
    7. 'Cache-Control': 'no-cache'
    8. }*/
    9. });
    10.  
    11. /* 请求拦截器 */
    12. service.interceptors.request.use((config) => {
    13. // 在这里配置请求 config
       return config;
    14. }, (err) => {
    15. console.error('请求发生了错误', err);
    16. return Promise.reject(err);
    17. });
    18.  
    19. /* 响应拦截器 */
    20. service.interceptors.response.use((res) => {
    21. // 在这里配置响应拦截器
    22. return res;
    23. }, (err) => {
    24. console.error('响应发生了错误', err);
    25. return Promise.reject(err);
    26. });
    27.  
    28. export default service;

    配置API调用方法:

    1. // 引入 axios 配置
    2. import service from './service';
    3. import qs from "qs";
    4.  
    5. // post 请求
    6. export function apiPost(data = {}) {
    7. return service({
    8. url: "接口url",
    9. method: 'post',
    10. data: qs.stringify(data),
    11. });
    12. }
    13.  
    14. // get 请求
    15. export function apiGet(params = {}) {
    16. return service({
    17. url: "接口url",
    18. method: 'get',
    19. params: params,
    20. });
    21. }
  • 配置跨域: Docs


    前面配置中 npm run eject 已经将配置暴露出来了
    1. npm install http-proxy-middleware --save

    2. cnpm i http-proxy-middleware -S

    src 下新建 setupProxy.js

    1. const proxy = require('http-proxy-middleware');
    2.  
    3. module.exports = function(app) {
    4. app.use(proxy('/api', { target: 'http://localhost:5000/' }));
    5. };
  • 安装配置路由 React-router:API Docs
    1. npm install react-router-dom --save

    2. cnpm install react-router-dom --save
    3. cnpm i react-router-dom -S

    单独新建一个 router.js:( 或者在入口文件 index.js 中写路由视图)

    1. import React from 'react';
    2. import { BrowserRouter as Router, Route } from 'react-router-dom';
    3. import YourComponent from 'your-component-path';
    4.  
    5. export default function () {
    6. return (
    7. <Router>
    8. <Route path='/' component={YourComponent} />
    9. </Router>
    10. );
    11. }

    然后在index.js里引用使用这个router.js:

    1. import Router from './path/router.js';
    2.  
    3. export default function Index() {
    4. return <Router />;
    5. }

    在哪个文件引用 router.js ,看个人项目构建喜好了,我是把 redux 和 antd 的配置 在 index.js 中引用的,把 router.js 在 app.js 中引用的,然后再把 app.js 引入到 index.js 中。
    可以看我 GitHub 的 mixins-demo

  • 安装配置 redux react-redux Docsredux Docs中文Docs
    1. npm install redux redux-thunk react-redux --save

    2. cnpm install redux redux-thunk react-redux --save
    3. cnpm i redux redux-thunk react-redux -S

    在src目录下新建 redux 文件夹,作为配置 redux 的目录:

    actions: 针对不同功能模块进行配置的 actions 文件放在此目录
    reducers: 针对不同功能模块进行配置的 reducers 文件放在此目录
    reducers.js: 把所有reducers 结合起来
    store.js: 对 redux 的配置文件
    types.js: 存放Actions中所需要的 type 属性值

    各文件代码:
    types.js:

    1. export const MYTODO = 'MYTODO';
    2. export const MYLIST = 'MYLIST';
    3. export const OTHERTODO = 'OTHERTODO';
    4. export const OTHERLIST = 'OTHERLIST';

    myReducer.js:

    1. import { MYTODO, MYLIST } from '../types';
    2. const initState = {
    3. myTodos: [],
    4. list: [],
    5. // ...etc.
    6. };
    7. export default function (state = initState, action) {
    8. switch (action.type) {
    9. case MYTODO:
    10. return {
    11. ...state,
    12. myTodos: action.payload
    13. };
    14. case MYLIST:
    15. return {
    16. ...state,
    17. list: action.payload
    18. };
    19. default:
    20. return state;
    21. }
    22. }

    myActions.js:

    1. import { MYTODO, MYLIST } from "../types";
    2.  
    3. export const myTodos = (params) => (dispatch, getState) => {
    4. // const { myState, otherState } = getState();
    5. dispatch({
    6. type: MYTODO,
    7. payload: params
    8. });
    9. };
    10. export const handleMyList = (params) => (dispatch, getState) => {
    11. // const { myState, otherState } = getState();
    12. dispatch({
    13. type: MYLIST,
    14. payload: params
    15. });
    16. };

    otherReducer.js:

    1. import { OTHERTODO, OTHERLIST } from '../types';
    2. const initState = {
    3. otherTodos: [],
    4. list: [],
    5. // ...etc.
    6. };
    7. export default function (state = initState, action) {
    8. switch (action.type) {
    9. case OTHERTODO:
    10. return {
    11. ...state,
    12. otherTodos: action.payload
    13. };
    14. case OTHERLIST:
    15. return {
    16. ...state,
    17. list: action.payload
    18. };
    19. default:
    20. return state;
    21. }
    22. }

    otherActions.js:

    1. import { OTHERTODO, OTHERLIST } from "../types";
    2.  
    3. export const otherTodos = (params) => (dispatch, getState) => {
    4. // const { myState, otherState } = getState();
    5. dispatch({
    6. type: OTHERTODO,
    7. payload: params
    8. });
    9. };
    10. export const handleOtherList = (params) => (dispatch, getState) => {
    11. // const { myState, otherState } = getState();
    12. dispatch({
    13. type: OTHERLIST,
    14. payload: params
    15. });
    16. };

    reducers.js:

    1. import { combineReducers } from 'redux';
    2. import myReducer from './reducers/myReducer';
    3. import otherReducer from './reducers/otherReducer';
    4.  
    5. export default combineReducers({
    6. myState: myReducer,
    7. otherState: otherReducer,
    8. });

    store.js:

    1. import { createStore, applyMiddleware, compose } from 'redux';
    2. import thunk from 'redux-thunk';
    3. import reducers from './reducers';
    4.  
    5. const initState = {};
    6. const middleware = [thunk];
    7.  
    8. const composeEnhancers =
    9. typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    10. ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
    11. : compose;
    12.  
    13. const enhancer =
    14. process.env.NODE_ENV === 'development'
    15. ? composeEnhancers(applyMiddleware(...middleware))
    16. : applyMiddleware(...middleware);
    17.  
    18. export const store = createStore(reducers, initState, enhancer);

    以上Redux基本配置完成,下面是调用方法:

    1. import React, { useEffect } from 'react';
    2. import PropTypes from 'prop-types';
    3. import { connect } from 'react-redux';
    4. import { myTodos, handleMyList } from './path/redux/actions/myActions';
    5.  
    6. function MyTodosComponent() {
    7. useEffect(() => {
    8. // 通过this.props 访问 state
    9. console.log(this.props.myTodos);
    10. console.log(this.props.list);
    11. // 调用 actions
    12. const todos = [
    13. {
    14. id: 1,
    15. todo: 'say hello world'
    16. }
    17. ];
    18. this.props.myTodos(todos);
    19. const list = [
    20. {
    21. id: 1,
    22. text: 'test',
    23. },
    24. ];
    25. this.props.handleMyList(list);
    26. }, []);
    27. return (
    28. <div>
    29. {
    30. this.props.todos.map((item, index) => {
    31. return (
    32. <div>id:{item.id}, todo:{item.todo}</div>
    33. );
    34. })
    35. }
    36. </div>
    37. );
    38. }
    39. // 类型检查
    40. MyTodosComponent.propTypes = {
    41. myTodos: PropTypes.array.isRequired,
    42. list: PropTypes.array.isRequired,
    43. };
    44. // 把redux中的state绑定到组件的props上
    45. const mapStateToProps = (state) => {
    46. const { myTodos, list } = state.myState;
    47. return {
    48. myTodos,
    49. list,
    50. };
    51. };
    52. // 把redux和组件结合起来,使组件能在props中访问到state和actions
    53. export default connect(
    54. mapStateToProps,
    55. {
    56. myTodos,
    57. handleMyList,
    58. },
    59. )(MyTodosComponent);

    以上代码只是示例,只需要关注配置和使用方法即可

    更多demo示例请看我的GitHub

React搭建项目(全家桶)的更多相关文章

  1. react 项目全家桶构件流程

    资源:create-react-app.react.react-dom.redux.react-redux.redux-thunk.react-router-dom.antd-mobile/antd. ...

  2. 如何使用React搭建项目

    1.首先说明node.js.npm.cnpm分别是做什么的? node.js简单的说 Node.js 就是运行在服务端的 JavaScript,安装了node.js默认安装了npm,可以使用npm - ...

  3. 使用webpack和react搭建项目

    看了N多博客,日志,一边迷茫一边摸索.本文记录流程.我怕自己忘了...并且修复了博客园首页推荐那个日志中遇到的bug 1.webstorm新建一个空白项目,比如webpack_demo 2.因为要用r ...

  4. 搭建vue全家桶

    1.直接利用vue-cli脚手架快速搭建 (1)全局安装vue-cli npm install -g vue-cli (2)创建项目 vue init webpack-simple my-projec ...

  5. react搭建项目

    1.创建react项目 使用react脚手架create-react-app npm install -g create-react-app create-react-app my-app cd my ...

  6. react全家桶从0搭建一个完整的react项目(react-router4、redux、redux-saga)

    react全家桶从0到1(最新) 本文从零开始,逐步讲解如何用react全家桶搭建一个完整的react项目.文中针对react.webpack.babel.react-route.redux.redu ...

  7. 使用React全家桶搭建一个后台管理系统

    引子 学生时代为了掌握某个知识点会不断地做习题,做总结,步入岗位之后何尝不是一样呢?做业务就如同做习题,如果‘课后’适当地进行总结,必然更快地提升自己的水平. 由于公司采用的react+node的技术 ...

  8. react-music React全家桶项目,精品之作!

    React-Music 全家桶项目,精品之作! 一.简介 该项目是基于React全家桶开发的一个音乐播放器,技术栈采用:Webpack + React + React-redux + React-ro ...

  9. 【实战】Vue全家桶(vue + axios + vue-router + vuex)搭建移动端H5项目

    使用Vue全家桶开发移动端页面. 本博文默认已安装node.js. github链接 一.准备工作 安装vue npm install vue 安装脚手架vue-cli npm install -g ...

随机推荐

  1. 纵论WebAssembly,JS在性能逆境下召唤强援

    webassembly的作用 webassembly是一种底层的二进制数据格式和一套可以操作这种数据的JS接口的统称.我们可以认为webassembly的范畴里包含两部分 wasm: 一种体积小.加载 ...

  2. NSAttributedString可以强制转换为NSMutableAttributedString类型吗?下面这代码有什么问题 为什么报错

    -(void)insetEmotion:(EmotionModel*)emotionModel{ if(emotionModel.code){ /** 在TextView中插入图片首选要知道光标的位置 ...

  3. Python-车牌识别

    一.车牌识别系统的用途与技术车牌识别系统(Vehicle License Plate Recognition,VLPR) 是计算机视频图像识别技术在车辆牌照识别中的一种应用.车牌识别在高速公路车辆管理 ...

  4. vue基本开发环境搭建

    先安装node运行环境下载网址 https://nodejs.org/en/或者http://nodejs.cn/ 检查node是否安装成功命令行窗口直接输入 $ node -v 如果输出版本号,说明 ...

  5. Ubuntu 18.04 LTS上安装NFS服务器和客户端

    NFS是基于UDP/IP协议的应用,其实现主要是采用远程过程调用RPC机制,RPC提供了一组与机器.操作系统以及低层传送协议无关的存取远程文件的操作.RPC采用了XDR的支持.XDR是一种与机器无关的 ...

  6. 批量注释 control+/

    批量注释 control+/ You can comment and uncomment lines of code using Ctrl+斜杠.Ctrl+斜杠 comments or uncomme ...

  7. Spring Quartz定时任务设置

    这里主要记录一下定时任务的配置,偏向于记录型的一个教程,这里不阐述Quartz的原理. 首先,在Spring配置文件里配置一个自己写好的一个包含执行任务方法的一个类. <bean id=&quo ...

  8. 关于简单的Excel多页签底层导出_电子底账导出为例(.net core)

    [HttpPost] public ActionResult ExpEleAcc(string linknos) { string filenname = null; CommonResult< ...

  9. Cisco 7200 路由 PPPOE 拨号详解

    1.1配置虚拟拨号接口 R1(config)#vpdn enable                  #启用vpdn虚拟专用拨号网络 R1(config)#interface dialer 1    ...

  10. openstack Mitaka实验环境安装(centos系统)

    本博文仅供参考,具体一定详细学习官方安装文档. 一 准备工作 二安装过程 1 安装NTP服务 2 安装openstack包 3 SQL数据库安装 4 安装消息队列 message queue 5 Me ...