使用react实现简单的ATM机的操作效果
时间: 2024-03-23 20:38:01 浏览: 12
好的,下面是一个使用 React 实现简单 ATM 操作效果的示例代码:
```jsx
import React, { useState } from "react";
function ATM() {
const [balance, setBalance] = useState(0);
const [withdrawAmount, setWithdrawAmount] = useState("");
const handleWithdraw = (e) => {
e.preventDefault();
if (withdrawAmount > balance) {
alert("余额不足!");
} else if (withdrawAmount <= 0) {
alert("请输入有效金额!");
} else {
setBalance(balance - withdrawAmount);
setWithdrawAmount("");
alert(`取款成功!余额为 ${balance - withdrawAmount} 元。`);
}
};
const handleDeposit = (e) => {
e.preventDefault();
if (withdrawAmount <= 0) {
alert("请输入有效金额!");
} else {
setBalance(balance + parseFloat(withdrawAmount));
setWithdrawAmount("");
alert(`存款成功!余额为 ${balance + parseFloat(withdrawAmount)} 元。`);
}
};
return (
<div>
<h1>ATM 机</h1>
<h2>余额:{balance} 元</h2>
<form onSubmit={handleWithdraw}>
<label>
取款金额:
<input
type="number"
value={withdrawAmount}
onChange={(e) => setWithdrawAmount(e.target.value)}
/>
</label>
<button type="submit">取款</button>
</form>
<form onSubmit={handleDeposit}>
<label>
存款金额:
<input
type="number"
value={withdrawAmount}
onChange={(e) => setWithdrawAmount(e.target.value)}
/>
</label>
<button type="submit">存款</button>
</form>
</div>
);
}
export default ATM;
```
这个简单的 ATM 组件包含一个余额显示、一个取款表单和一个存款表单。用户可以在表单中输入金额,然后通过点击“取款”或“存款”按钮来完成对余额的更改。在用户操作时,组件会检查输入的金额是否合法,并在成功修改余额后弹出一条提示信息。
需要注意的是,这个组件并没有实现任何真正的银行操作,仅仅是一个简单的前端界面。如果您需要将其应用到真实的银行系统中,需要注意数据安全和业务逻辑的实现。