首页 > 解决方案 > 如何通过 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()方法需要时间,我想更改窗口,以便在执行时用户可以看到进度条或类似的东西。

标签: javascriptreactjsaxiosloadingsweetalert2

解决方案


我做了一些研究,我找到了解决方案。

实际上,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


推荐阅读