javascript - 如何通过 React JS 向 sweetalert2 的对话框添加加载方法?
问题描述
我正在编写一个记录音频并将其发送到后端服务器的网络项目。
用户完成录制后,我正在使用 sweetalert2Swal.fire()
显示成功消息并获取完成该过程所需的用户输入(将创建的 PDF 的标题)。
当用户按下提交按钮时,axios
会向服务器发送一个请求,这需要几秒钟。
现在在我的代码中,当按下 sweetalert 的“提交”按钮时,弹出窗口关闭,用户应该等待,没有任何指示页面正在等待响应。
我的问题是:如何更改弹出窗口的内容以让用户知道使用sweetalert2
's interface 的加载(或者是否有更好的方法)?
Swal.fire()
代码:
const stopRecording = () => {
// .. stop recording
Swal.fire({
icon: "success",
title: '<span style="color: white">Recording Saved!</span>',
text:
"Please Enter the Title for the Output Audio Sheets...\n You can press cancel and record again",
input: "text",
showCancelButton: true,
confirmButtonColor: "white",
confirmButtonText: '<span style="color: #191919">Submit</span>',
cancelButtonColor: "white",
cancelButtonText: '<span style="color: #191919">Cancel</span>',
customClass: "swal-confirm",
}).then((result) => {
if (!result.value) return;
else {
// .. getting the data and performing axios request
}
});
};
现在,当您阅读代码时,我可以更具体。该Swal.fire().then()
方法需要时间,我想更改窗口,以便在执行时用户可以看到进度条或类似的东西。
解决方案
我做了一些研究,我找到了解决方案。
实际上,sweetalert2
的对象有一个属性,就是这样的东西,它被称为preConfirm
。
它用于在窗口关闭之前发出 Web 请求或加载一些数据。
另外,有了这个属性,我避免了使用该.then()
方法,这使代码更加优雅和可读。
我现在的代码:
const saveRecording = (audioData) => {
// .. stop and save recording
Swal.fire({
// Swal properties
icon: "success",
title: '<span style="color: white">Recording Saved!</span>',
text:
"Please Enter the Title for the Output Audio Sheets...\n You can press cancel and record again",
input: "text",
inputPlaceholder: "Enter Your Title Here",
showCancelButton: true,
// input validator
inputValidator: (value) => {
if (!value) {
return "Title cannot be empty!";
}
},
// styles
confirmButtonColor: "white",
confirmButtonText: '<span style="color: #191919">Submit</span>',
cancelButtonColor: "white",
cancelButtonText: '<span style="color: #191919">Cancel</span>',
customClass: "swal-confirm",
// This is my solution
preConfirm: (title) => {
// .. axios request here using `title` as the input
},
allowOutsideClick: () => !Swal.isLoading(),
showLoaderOnConfirm: true,
});
};
您可以在AJAX
这里查看官方 sweetalert2 的请求示例:https ://sweetalert2.github.io/#ajax-request
推荐阅读
- json - 如何在包含接口类型集合的类上应用 JSON 补丁文档
- python - 插入新行并重新启动获取代码时如何从 SQL Server 数据库中获取数据?
- ios - SwiftUI:如何在搜索栏的文本更改时触发 api 调用以检索数据源
- angular - 由于异常,Angular 防护未重定向到特定页面
- python - Python 多处理程序没有充分利用 Windows 上的 CPU 资源
- python - Python中更高效/简化的数据框滚动窗口计算
- hive - 将 Hive 输出存储为文本文件
- python-2.7 - AttributeError:“模块”对象没有属性“FalseNegatives”
- javascript - 从 Props 中检索数据数组
- javascript - 当页面url更改但不是在jquery中刷新时如何删除cookie?