React+Antd全局加载遮罩工具

下面是全局加载遮罩工具,功能:提供show和showWithDelay/hide方法用于显示/延时显示/隐藏遮罩,它还提供loading属性返回是否正在loading。通常用于耗时较长的操作,比如远端api调用。

如何用它,下面是个例子,这个是全局的postAction:

javascript 复制代码
import loadingMask from './loadingMask';
...
// 设置延迟显示加载遮罩(1秒后显示)
  loadingMask.showWithDelay('请求处理中,请稍候...', 1000);

  return axios({
    url: url,
    method: 'post',
    data: parameter,
    headers: { ...signHeader, ...config.headers },
    ...config
  }).then(res => {
    // 请求完成后隐藏加载遮罩
    loadingMask.hide();
    return handleResponse(res);
  }).catch(err => {
    // 请求出错后隐藏加载遮罩
    loadingMask.hide();
    return handleError(err);
  });

如果想实时获得它的loading属性呢?这时候要订阅它的状态变化:

javascript 复制代码
const [loading, setLoading] = useState(loadingMask.loading);
// 订阅 loadingMask 的 loading 状态变化
    useEffect(() => {
        // 订阅 loading 状态变化
        const unsubscribe = loadingMask.subscribeToLoading(setLoading);

        // 组件卸载时取消订阅
        return unsubscribe;
    }, []);
    ...
    <Button
                        block
                        type='submit'
                        color='primary'
                        loading={loading}
                    >
                        删除选中记录
                    </Button>

这时候loadingMask的loading状态变化会立即返回到setLoading,也就会引导起button的重新渲染。

组件代码如下:

javascript 复制代码
import React from 'react';
import { createRoot } from 'react-dom/client';
import { Mask, SpinLoading } from 'antd-mobile';
import styled from 'styled-components';

const LoadingContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
`;

const LoadingText = styled.div`
  margin-top: 12px;
  font-size: 14px;
`;

/**
 * 全局加载遮罩工具
 * 用于在长时间请求时显示加载遮罩
 */
class LoadingMask {
  constructor() {
    this.container = null;
    this.root = null;
    this.visible = false;
    this.timeoutId = null;
    this.loadingText = '正在加载,请稍候...';
    this._loading = false; // 添加内部 loading 状态
    this._listeners = []; // 添加监听器数组
    this.init();
  }

  /**
   * 初始化加载遮罩容器
   */
  init() {
    // 创建容器元素
    this.container = document.createElement('div');
    this.container.id = 'global-loading-mask-container';
    document.body.appendChild(this.container);
    
    // 创建React 18的root
    this.root = createRoot(this.container);
    
    // 初始渲染
    this.render();
  }

  /**
   * 渲染加载遮罩
   */
  render() {
    if (!this.root) {
      this.init();
      return;
    }

    this.root.render(
      <Mask opacity={0.7} visible={this.visible}>
        <LoadingContainer>
          <SpinLoading color='white' style={{ '--size': '48px' }} />
          <LoadingText>{this.loadingText}</LoadingText>
        </LoadingContainer>
      </Mask>
    );
  }

  /**
   * 显示加载遮罩
   * @param {string} text - 加载提示文本
   */
  show(text) {
    this.loadingText = text || '正在加载,请稍候...';
    this.visible = true;
    this._setLoading(true); // 使用新方法设置 loading 状态
    this.render();
  }

  /**
   * 隐藏加载遮罩
   */
  hide() {
    this.visible = false;
    this._setLoading(false); // 使用新方法设置 loading 状态
    this.render();

    // 清除定时器
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.timeoutId = null;
    }
  }

  /**
   * 设置延迟显示加载遮罩
   * @param {string} text - 加载提示文本
   * @param {number} delay - 延迟时间(毫秒)
   */
  showWithDelay(text, delay = 1000) {
    // 清除之前的定时器
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    
    // 立即设置 loading 状态为 true
    this.loadingText = text || '正在加载,请稍候...';
    this._setLoading(true); // 使用新方法设置 loading 状态

    // 设置新的定时器,只延迟显示遮罩
    this.timeoutId = setTimeout(() => {
      this.visible = true;
      this.render();
    }, delay);
  }

  // 添加设置 loading 状态的方法,并通知监听器
  _setLoading(value) {
    if (this._loading !== value) {
      this._loading = value;
      // 通知所有监听器
      this._listeners.forEach(listener => listener(value));
    }
  };

  // 添加订阅方法
  subscribeToLoading(callback) {
    this._listeners.push(callback);
    // 立即通知当前状态
    callback(this._loading);
    
    // 返回取消订阅的函数
    return () => {
      this._listeners = this._listeners.filter(cb => cb !== callback);
    };
  };
}


// 创建单例实例
const loadingMask = new LoadingMask();

// 添加 loading 属性的 getter
Object.defineProperty(loadingMask, 'loading', {
  get: function() {
    return this._loading;
  }
});

export default loadingMask;
相关推荐
夕水3 小时前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript
时间的情敌4 小时前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
Amumu121384 小时前
TypeScript学习: 基本类型(一)
开发语言·前端·typescript
光影少年5 小时前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈
bai2735 小时前
主线程里 foo 和 FOO 是同一个变量,Worker 里就成了两个:Windows 上 process.env 的大小写边界
javascript·后端
颜进强6 小时前
切个 Tab,接口全串号了——我用 AsyncLocalStorage 一招根治
前端·ai编程·全栈
code2cat6 小时前
React入门之任务列表:交换两行后,展开的详情跟着谁走
前端·javascript·react.js
map_3d_vis7 小时前
JSAPI 4.0 默认行为一览:滚轮缩放、默认视野、缩放范围和 addLayer
前端·javascript·地图·百度地图
钱栈up11 小时前
均值虚线静默消失三天,零报错零告警——一次匹配逻辑 P0 事故的完整复盘
前端·数据可视化
FanetheDivine14 小时前
总结近期关于Agent的思考和成果
javascript·agent·ai编程