【问题标题】:How can I add a loading method to a sweetalert2's dialogt via React JS?如何通过 React JS 向 sweetalert2 的对话框添加加载方法?
【发布时间】:2021-03-26 15:59:02
【问题描述】:

我正在编写一个记录音频并将其发送到后端服务器的网络项目。

用户完成录制后,我正在使用 sweetalert2 的 Swal.fire() 来显示成功消息并获取完成该过程所需的用户输入(将创建的 PDF 的标题)。

当用户按下提交按钮时,会向服务器发送一个axios 请求,这需要几秒钟时间。

现在在我的代码中,当按下 sweetalert 的“提交”按钮时,弹出窗口关闭,用户应该等待,而没有任何指示页面正在等待响应。

我的问题是:如何使用sweetalert2 的界面更改弹出窗口的内容以让用户知道其加载(或者是否有更好的方法)?

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

【问题讨论】:

  • 可以通过设置间隔或使用 axios onProgress 来解释 here

标签: javascript reactjs axios loading sweetalert2


【解决方案1】:

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

实际上,sweetalert2 的对象有一个专门用于此类内容的属性,称为preConfirm

它用于在窗口关闭之前发出网络请求或加载一些数据。

另外,有了这个属性,我避免使用.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,
    });
  };

您可以在此处查看官方 sweetalert2 发出AJAX 请求的示例:https://sweetalert2.github.io/#ajax-request

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多