[英]Prevent Clicking Again When Submitting Form in React
I have a form in my React app and i wanted to disable or not be able to click the Pay
button once i have submitted it.我的 React 应用程序中有一个表单,我想在提交后禁用或无法单击“ Pay
按钮。 The problem is, that it is not submitting through API but through a <form>
.问题是,它不是通过 API 提交,而是通过<form>
提交。
Form形式
<form ref={formEl} action="https://sample.aspx" method="POST">
<input name="order" id="order" value={base64String} readOnly type="hidden" />
</form>
Button按钮
<Button onClick={() => onPay(order.id)}>Pay</Button>;
Pay Function支付功能
const onPay = (id) => {
formEl.current && formEl.current.submit();
};
If you want to implement this functionality, you should use form event onSubmit
.如果你想实现这个功能,你应该使用表单事件onSubmit
。 Use any HTTP client like fetch or axios to call API.使用任何 HTTP 客户端(如 fetch 或 axios)来调用 API。 You can use a state value to track submission status.您可以使用状态值来跟踪提交状态。
Form形式
<form ref={formEl} action="https://sample.aspx" method="POST" onSubmit={onSubmit}>
<input name="order" id="order" value={base64String} readOnly type="hidden" />
</form>
Button按钮
<Button onClick={() => onPay(order.id)}>Pay</Button>;
State状态
const [submitting, setSubmitting] = useState(false)
Pay Function支付功能
const onPay = (id) => {
if (submitting) return;
formEl.current && formEl.current.submit();
};
Submit Function提交功能
const onSubmit = async (event) => {
event.preventDefault();
setSubmitting(true);
await fetch('https://sample.aspx');
setSubmitting(false);
}
You can use boolean value to disable and enable it within useState.您可以使用布尔值在 useState 中禁用和启用它。
const [_boolValue, setBoolValue] = useState(true); <Button onClick={() => { setBoolValue(!_boolValue) onPay(order.id) }}>Pay</Button>;
then it will work only _boolValue == true
那么它只会工作_boolValue == true
const onPay = (id) => { _boolValue && formEl.current && formEl.current.submit(); };
You can use useState
to keep track of when the button is clicked:您可以使用useState
来跟踪单击按钮的时间:
const [paid, setPaid] = useState(false)
Then set the button's enabled
state based on the above.然后根据上面的设置按钮的enabled
状态。 You can toggle the boolean within your onPay
function.您可以在onPay
函数中切换布尔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.