Web学习(十)React实战-计算器

1.创建项目

create-react-app calculator

然后安装bootstrap,redux,route

npm i bootstrap
npm i redux react-redux @reduxjs/toolkit
npm i react-router-dom

2.编写基本组件并添加路由

Navbar.jsx:
从bootstrap上选择一种样式,a标签改为link(为了实现页面跳转)

import React, { Component } from 'react';
import {Link} from 'react-router-dom';class NavBar extends Component {state = {  } render() { return (<nav className="navbar navbar-expand-lg navbar-light bg-light"><div className="container"><Link className="navbar-brand" to="/">Web</Link><button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"><span className="navbar-toggler-icon"></span></button><div className="collapse navbar-collapse" id="navbarText"><ul className="navbar-nav me-auto mb-2 mb-lg-0"><li className="nav-item"><Link className="navbar-brand" to="/home">首页</Link></li><li className="nav-item"><Link className="navbar-brand" to="/calculator">计算器</Link></li></ul><ul className="navbar-nav"><li className="nav-item"><Link className="navbar-brand" to="/login">登录</Link></li><li className="nav-item"><Link className="navbar-brand" to="/register">注册</Link></li></ul></div></div></nav>);}
}export default NavBar;

在App.jsx中添加路由:

import React, { Component } from 'react';
import NavBar from './NavBar';
import {Routes, Route, Navigate} from 'react-router-dom';
import Home from './content/home';
import Calculator from './content/calculator';
import Login from './content/login';
import Register from './content/register';
import NotFound from './content/notFound';class App extends Component {state = {  } render() { return (<React.Fragment><NavBar /><div className='container'><Routes><Route path='/' element={<Home />} /><Route path='/home' element={<Home />} /><Route path='/calculator' element={<Calculator />} /><Route path='/login' element={<Login />} /><Route path='/register' element={<Register />} /><Route path='/404' element={<NotFound />} />{/* 重定向,不存在的页面指向404 */}<Route path="*" element={ <Navigate replace to="/404" /> } /></Routes></div></React.Fragment>);}
}export default App;

编写Base组件作为模板,将其他页面内容放入Base中。
Base.jsx:

import React, { Component } from 'react';class Base extends Component {state = {  } render() { return (<div className="card" style={{marginTop: "20px"}}><div className="card-body">{this.props.children}</div></div>);}
}export default Base;

在其他模块中使用Base:
以home.jsx为例:

import React, { Component } from 'react';
import Base from './base';class Home extends Component {state = {  } render() { return (<Base>首页</Base>);}
}export default Home;

3.编写计算器页面

calculator.jsx:

import React, { Component } from 'react';
import Base from './base';class Calculator extends Component {state = {  } render() { return (<Base><div className="calculator"><div className="output"><div className="last-output">123 *</div><div className="current-output">9696969696</div></div><button className='button-ac'>AC</button><button>Del</button><button>/</button><button>7</button><button>8</button><button>9</button><button>*</button><button>4</button><button>5</button><button>6</button><button>-</button><button>1</button><button>2</button><button>3</button><button>+</button><button>0</button><button>.</button><button className='button-equal'>=</button></div></Base>);}
}export default Calculator;

index.css:

body {margin: 0;
}* {box-sizing: border-box;
}.calculator {display: grid;grid-template-columns: repeat(4, 6rem);grid-template-rows: minmax(6rem, auto) repeat(5, 4rem);gap: 1px;background-color: rgba(191,191,191, 0.75);width: calc(24rem + 5px);margin: 0 auto;border: 2px solid black;
}.output {grid-column: 1 / span 4;display: flex;flex-direction: column;align-items: flex-end;justify-content: space-around;padding: 10px;word-wrap: break-word;word-break: break-all;
}.last-output {}.current-output {font-size: 3rem;}.button-ac {grid-column: 1 / span 2;
}.button-equal {grid-column: 3 / span 2;
}.calculator > button {background-color: rgba(250,250,249, 0.75);
}.calculator > button:hover {background-color: #B5B5B5;
}

4.创建redux文件夹

创建redux文件夹并创建文件actions.js,reducer.js,store.js

  • store:存储树结构。
  • state:维护的数据,一般维护成树的结构。
  • reducer:对state进行更新的函数,每个state绑定一个reducer。传入两个参数:当前state和action,返回新state。
  • Provider组件:用来包裹整个项目,其store属性用来存储redux的store对象

actions.js:

// 储存四种操作
const ACTIONS = {ADD_DIGIT: "add-digit",DELETE_DIGIT: "delete-digit",CHOOST_OPERATION: "choose-operation",CLEAR: "clear",EVALUATE: "evaluate"
};export default ACTIONS;

store.js:

import { configureStore } from "@reduxjs/toolkit"
import reducer from "./reducer";const store = configureStore({reducer
});export default store;

将index.js中内容放入Provider中:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './component/App';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/js/bootstrap'
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import store from './redux/store';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Provider store={store}><BrowserRouter><App /></BrowserRouter></Provider>);

5.添加digitButton组件

在component/content文件夹下创建calculator文件夹用于存放digitButton组件
digitButton.jsx

import React, { Component } from 'react';
import ACTIONS from '../../../redux/actions';
import { connect } from 'react-redux';class DigitButton extends Component {state = {  };render() { return (// 点击触发add_digit增加数字操作<button onClick={() => this.props.add_digit(this.props.digit)}> {this.props.digit}</button>);}
}// mapStateToProps:每次store中的状态更新后调用一次,用来更新组件中的值。
const mapDispatchToProps = {add_digit: digit => {return {type: ACTIONS.ADD_DIGIT,digit: digit,}}
}// connect(mapStateToProps, mapDispatchToProps)函数:用来将store与组件关联起来
export default connect(null, mapDispatchToProps)(DigitButton);

将calculator.jsx中button换为digitButton,并显示出数字:

import React, { Component } from 'react';
import Base from './base';
import { connect } from 'react-redux';
import DigitButton from './calculator/digitButton';class Calculator extends Component {state = {  } render() { return (<Base><div className="calculator"><div className="output">{/* 显示上一个数字,操作符与当前数字 */}<div className="last-output">{this.props.lastOperand} {this.props.operation}</div><div className="current-output">{this.props.currentOperand}</div></div><button className='button-ac'>AC</button><button>Del</button><button>/</button><DigitButton digit={"7"} /><DigitButton digit={"8"} /><DigitButton digit={"9"} /><button>*</button><DigitButton digit={"4"} /><DigitButton digit={"5"} /><DigitButton digit={"6"} /><button>-</button><DigitButton digit={"1"} /><DigitButton digit={"2"} /><DigitButton digit={"3"} /><button>+</button><DigitButton digit={"0"} /><DigitButton digit={"."} /><button className='button-equal'>=</button></div></Base>);}
}// 组件创建时调用一次,用来将store的dispatch函数传入组件
const mapStateToProps = (state, props) => {return {currentOperand: state.currentOperand,lastOperand: state.lastOperand,operation: state.operation,}
};export default connect(mapStateToProps)(Calculator);

在reducer中实现add_digit逻辑:

import ACTIONS from "./actions"const reducer = (state={currentOperand: "",lastOperand: "",operation: "",overwrite: false,
}, action) => {switch(action.type) {case ACTIONS.ADD_DIGIT:if (state.overwrite)return {...state,currentOperand: action.digit,overwrite: false}if (state.currentOperand === '0' && action.digit === '0')return state;if (state.currentOperand === '0' && action.digit !== '.')return {...state,currentOperand: action.digit,}if (action.digit === '.' && state.currentOperand.includes('.'))return state;if (action.digit === '.' && state.currentOperand === "")return {...state,currentOperand: "0."};return {...state,currentOperand: state.currentOperand + action.digit,}default:return state;}
};export default reducer;

Web学习(十)React实战-计算器相关推荐

  1. React学习(十)-React中编写样式CSS(styled-components)

    虽互不曾谋面,但希望能和你成为笔尖下的朋友 以读书,技术,生活为主,偶尔撒点鸡汤 不作,不敷衍,意在真诚吐露,用心分享 点击左上方,可关注本刊 撰文 | 川川 VX-ID:suibichuanji 点 ...

  2. tensorflow 语义slam_研究《视觉SLAM十四讲从理论到实践第2版》PDF代码+《OpenCV+TensorFlow深度学习与计算机视觉实战》PDF代码笔记...

    我们知道随着人工神经网络和深度学习的发展,通过模拟视觉所构建的卷积神经网络模型在图像识别和分类上取得了非常好的效果,借助于深度学习技术的发展,使用人工智能去处理常规劳动,理解语音语义,帮助医学诊断和支 ...

  3. 【Youtobe trydjango】Django2.2教程和React实战系列十【动态路由、app内部路由】

    [Youtobe trydjango]Django2.2教程和React实战系列十[动态路由.app内部路由] 1. 动态路由示例 1.1 动态路由 1.2 处理DoesNotExist不存在 2. ...

  4. web python识花_TensorFlow迁移学习识花实战案例

    TensorFlow 迁移学习识花实战案例 本文主要介绍如何使用迁移学习训练图片识别花朵的模型,即识别出图片上是何种花朵. 本文档中涉及的演示代码和数据集来源于网络,你可以在这里下载到:TRANSFE ...

  5. Web前端技术 Web学习资料 Web学习路线 Web入门宝典

    学习路线 第一章 核心 1.Node Node.js 就是运行在服务端的 JavaScript.Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台.Node.js是一个 ...

  6. Web前端技术 Web学习资料 Web学习路线 Web入门宝典(不断更新中)

    (此文档于2019年3月停止再更新,后续更新移步至:https://github.com/liuyuqin1991/polaris) 学习路线 第一章 技术(核心单独列章节) 1.Node Node. ...

  7. LSTM之父发文:我眼中的深度学习十年简史!

    点击上方"开发者技术前线",选择"星标" 13:21 在看 真爱 作者 | Jürgen Schmidhuber 编译 | 刘畅.若名  出品 | AI科技大本 ...

  8. Redis学习笔记(实战篇)(自用)

    Redis学习笔记(实战篇)(自用) 本文根据黑马程序员的课程资料与百度搜索的资料共同整理所得,仅用于学习使用,如有侵权,请联系删除 文章目录 Redis学习笔记(实战篇)(自用) 1.基于Sessi ...

  9. 最新web学习路线及课程大纲

    学习web前端的同学越来越多,怎么学,从哪里开始学可能很多同学都摸不到头脑,那么今天就给大家分享web前端学习路线及课程大纲给大家,相信有了这份web前端工程师教程大纲大家能更清晰的找到自己的学习路径 ...

最新文章

  1. 如何写好一篇科技论文?以Wiley科技刊为例(附视频)
  2. vue修饰符 .lazy .number .trim
  3. 用 python 解决汉诺塔问题并附带演示过程
  4. 不仅能搜索还能查信息 带你了解LBS应用
  5. Spring Boot 2.0.5 配置Druid数据库连接池
  6. 基于modbus协议的工业自动化网络规范_工控学堂:解读Modbus通讯协议「宜收藏」...
  7. 「C++: Eigen」学习笔记
  8. 【高清】鲁邦三世主题曲 - ルパン三世のテーマ'80 南澤大介 改编+演奏
  9. SAP Intelligent Robotic Process Automation权限控制
  10. Bootstrap 两端对齐的导航
  11. NS3 MyApp Class Reference
  12. php滑动轮播效果,js实现移动端手指滑动轮播图效果
  13. 在考纲词汇中利用复数规则找出的65个词
  14. 最简单的TCP网络封包解包(补充)-序列化
  15. CompletableFuture 使用详解
  16. uni中一些插件的使用
  17. jsp文字上下居中显示_div+css:页面整体布局居中显示:上下居中||垂直居中,左右居中||水平居中...
  18. winform高仿腾讯QQ2013,几十个界面哦!!
  19. linux:The CXX compiler identification is unknown
  20. 涂涂乐的详细实现之一--画笔核心功能

热门文章

  1. QVariant 类的应用
  2. Git回滚版本并push到远端master
  3. java 面向对象1
  4. Synchronized 和 Lock 的区别和使用场景
  5. Word文档中如何从第三页开始设置页码
  6. Redux-Saga在React工程架构之的应用实践详解
  7. 后话:PipeLine支撑运维自动化
  8. Smartbi电子表格故事之高效营销活动后的自助数据分析
  9. TI AM3552开发板(arm cortex A8) 初体验
  10. angular $q promise详解