简易计算器
import React, { useState, useCallback, useReducer } from "react";
import { Input, Card } from 'antd';
import cx from 'classnames'
import './index.css'
const numList = [
{ key: 'one', children: [1, 2, 3, 4] },
{ key: 'two', children: [5, 6, 7, 8] },
{ key: 'three', children: [9, 0, '.'] },
]
const beHavior = [
{ key: 'add', title: '+' },
{ key: 'delete', title: '-' },
{ key: 'ride', title: '*' },
{ key: 'except', title: '/' },
{ key: 'result', title: '=' },
{ key: 'reset', title: 'del' },
]
const Algorithm = () => {
const getResult = (type, arr) => {
switch (type) {
case '+':
return parseFloat(arr[0]) + parseFloat(arr[1])
case '-':
console.log(arr);
return parseFloat(arr[0]) - parseFloat(arr[1])
case '*':
return parseFloat(arr[0]) * parseFloat(arr[1])
case '/':
return parseFloat(arr[0]) / parseFloat(arr[1])
default:
break;
}
}
const reducer = (state, action) => {
switch (action.type) {
case '=':
let res = inpValue && JSON.parse(JSON.stringify(inpValue))
let result = res.replace('=', '')
let arr = []
for (const value of beHavior) {
arr.push(value.title)
}
let resultArr
let getCalculationResult = 0
for (const key in arr) {
if (result.includes(arr[key])) {
resultArr = result.split(arr[key])
getCalculationResult = getResult(arr[key], resultArr)
}
}
setInpValue(value => {
return value = getCalculationResult
})
break;
case 'del':
setInpValue('')
break
default:
break;
}
}
const initData = {
content: 0
}
const [inpValue, setInpValue] = useState('')
const [state, dispath] = useReducer(reducer, initData)
const getNums = useCallback((value) => {
setInpValue(val => {
let newVal = val + value
return newVal
})
}, [])
return (
<div>
<h1>Algorithm</h1>
<Card title="Default size card" style={{ width: 300 }}>
{numList.map(item => {
const { key, children } = item
return (
<p key={key}>{
children.map(ele => {
return (
<span key={ele} className={cx('ele-span')} onClick={() => getNums(ele)}>{ele}</span>
)
})
}</p >
)
})}
<Input value={inpValue} />
{
beHavior.map(item => {
const { key, title } = item
return (
<span key={key} className={cx('ele-span', { beHavior: true })} onClick={() => {
dispath({ type: title })
getNums(title)
}}>{title}</span>
)
})
}
</Card>
</div>
)
}
export default Algorithm
@purple:#7735b4;
.ele-span{
width: 40px;
height: 40px;
border: 1px solid rosybrown;
display: inline-block;
margin-right: 5px;
text-align: center;
line-height: 40px;
}
.beHavior{
border-color: @purple;
margin-top: 5px;
}