在没有钩子的React App Calculator上实现不同的操作可以通过以下步骤完成:
以下是一个示例代码,演示了如何在没有钩子的React App Calculator上实现不同的操作:
import React, { useState } from 'react';
const Calculator = () => {
const [display, setDisplay] = useState('0');
const [prevOperand, setPrevOperand] = useState('');
const [operator, setOperator] = useState('');
const handleButtonClick = (value) => {
switch (value) {
case 'AC':
setDisplay('0');
setPrevOperand('');
setOperator('');
break;
case '=':
calculateResult();
break;
case '+':
case '-':
case '*':
case '/':
setOperator(value);
setPrevOperand(display);
setDisplay('0');
break;
default:
if (display === '0') {
setDisplay(value);
} else {
setDisplay(display + value);
}
break;
}
};
const calculateResult = () => {
const currentOperand = parseFloat(display);
const previousOperand = parseFloat(prevOperand);
let result = 0;
switch (operator) {
case '+':
result = previousOperand + currentOperand;
break;
case '-':
result = previousOperand - currentOperand;
break;
case '*':
result = previousOperand * currentOperand;
break;
case '/':
result = previousOperand / currentOperand;
break;
default:
return;
}
setDisplay(result.toString());
setPrevOperand('');
setOperator('');
};
return (
<div>
<div>{display}</div>
<button onClick={() => handleButtonClick('AC')}>AC</button>
<button onClick={() => handleButtonClick('+')}>+</button>
<button onClick={() => handleButtonClick('-')}>-</button>
<button onClick={() => handleButtonClick('*')}>*</button>
<button onClick={() => handleButtonClick('/')}>/</button>
<button onClick={() => handleButtonClick('7')}>7</button>
<button onClick={() => handleButtonClick('8')}>8</button>
<button onClick={() => handleButtonClick('9')}>9</button>
<button onClick={() => handleButtonClick('4')}>4</button>
<button onClick={() => handleButtonClick('5')}>5</button>
<button onClick={() => handleButtonClick('6')}>6</button>
<button onClick={() => handleButtonClick('1')}>1</button>
<button onClick={() => handleButtonClick('2')}>2</button>
<button onClick={() => handleButtonClick('3')}>3</button>
<button onClick={() => handleButtonClick('0')}>0</button>
<button onClick={() => handleButtonClick('=')}>=</button>
</div>
);
};
export default Calculator;
请注意,以上代码只是一个示例,仅包含基本的四则运算功能。你可以根据需求进行修改和扩展。此外,不同的操作可能需要引入其他依赖或组件,具体取决于你的实际需求。
领取专属 10元无门槛券
手把手带您无忧上云