咒語:利用mui的Button Grid 跟文字顯示框 製作出可加減乘除的計算機 並且附上邏輯 並且有0~9還有類似小算盤的排版 請不要省略
import React, { useState } from "react";
import { Grid, Button, TextField, styled } from "@mui/material";
const CalculatorStyle = styled("div")({
maxWidth: "400px",
margin: "0 auto",
padding: "10px",
textAlign: "center"
});
const Calculator = () => {
const [display, setDisplay] = useState("");
const handleButtonClick = (value) => {
if (value === "=") {
const parts = display.split(" ");
const num1 = parseFloat(parts[0]);
const operator = parts[1];
const num2 = parseFloat(parts[2]);
switch (operator) {
case "+":
setDisplay(num1 + num2);
break;
case "-":
setDisplay(num1 - num2);
break;
case "*":
setDisplay(num1 * num2);
break;
case "/":
setDisplay(num1 / num2);
break;
default:
setDisplay("");
}
} else if (value === "C") {
setDisplay("");
} else {
setDisplay(display + value);
}
};
return (
<CalculatorStyle>
<TextField
fullWidth
variant="outlined"
value={display}
InputProps={{ readOnly: true }}
/>
<Grid container spacing={1} style={{ marginTop: "10px" }}>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("7")}>
7
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("8")}>
8
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("9")}>
9
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("/")}>
/
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("4")}>
4
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("5")}>
5
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("6")}>
6
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("*")}>
*
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("1")}>
1
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("2")}>
2
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("3")}>
3
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("-")}>
-
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("0")}>
0
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("=")}>
=
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("+")}>
+
</Button>
</Grid>
<Grid item xs={3}>
<Button variant="contained" onClick={() => handleButtonClick("C")}>
C
</Button>
</Grid>
</Grid>
</CalculatorStyle>
);
};
export default Calculator;
這樣我們就可以用來計算 30-27 恩 還有三天