使用react实现一个简易计算器用两个input中间的加减乘除用select标签包住
时间: 2024-05-01 07:16:29 浏览: 200
这里是一个使用React实现的简易计算器,其中两个输入框用于输入数字,下拉菜单用于选择运算符,点击“计算”按钮后会在结果框中显示计算结果。
```jsx
import React, { useState } from "react";
function Calculator() {
const [num1, setNum1] = useState("");
const [num2, setNum2] = useState("");
const [operator, setOperator] = useState("+");
const [result, setResult] = useState("");
const calculateResult = () => {
let num1Val = parseFloat(num1);
let num2Val = parseFloat(num2);
let resultVal;
switch (operator) {
case "+":
resultVal = num1Val + num2Val;
break;
case "-":
resultVal = num1Val - num2Val;
break;
case "*":
resultVal = num1Val * num2Val;
break;
case "/":
resultVal = num1Val / num2Val;
break;
default:
resultVal = "";
break;
}
setResult(resultVal);
};
return (
<div>
<input
type="number"
value={num1}
onChange={(event) => setNum1(event.target.value)}
/>
<select
value={operator}
onChange={(event) => setOperator(event.target.value)}
>
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input
type="number"
value={num2}
onChange={(event) => setNum2(event.target.value)}
/>
<button onClick={calculateResult}>计算</button>
<div>结果:{result}</div>
</div>
);
}
export default Calculator;
```
阅读全文