React实现全局Loading

css

css 复制代码
#__loading {
  position:fixed;
  top: 0;
  left: 0;
  z-index: 99999;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0);
}

页面代码

使用了antd的Spin组件

javascript 复制代码
import React from 'react'
import ReactDOM from 'react-dom'
import { Spin } from 'antd'

class Loading {
    show (timeout) {
        const config = {
            tip: 'Loading...',
        }
        if (timeout) {
            window.setTimeout(() => {
                document.body.removeChild(document.getElementById('__loading'))
            }, timeout)
        }
        const dom = document.createElement('div')
        dom.setAttribute('id', '__loading')
        document.body.appendChild(dom)
        ReactDOM.render(<Spin {...config} />, dom)
    }
    hide() {
        document.body.removeChild(document.getElementById('__loading'))
    }
}

export default new Loading()

其实是没有必要使用antd的Spin组件,自己通过css实现一个Loading效果,网上百度一堆这种代码,我这里使用antd的组件是因为我自己项目使用了antd,保证组件风格统一性。

注意点:

刚开始我使用的css样式是position:absolute; 然后我发现我的Loading一会在页面中间,一会不在顶部。

通过查看css发现,自己的页面的body是可以滑动的,导致Loading位置时不时变化,如果页面不滑动Loading在页面中间,如果滑动就不在了。所以应该把css样式修改成position:fixed;就没问题了。(至于为啥自己页面body为啥可以滑动,是因为自己项目问题)。

推广一下自己开发的微信小程序,有兴趣的朋友可以玩一玩

相关推荐
前端小趴菜051 分钟前
React - 组件通信
前端·react.js·前端框架
Amy_cx21 分钟前
在表单输入框按回车页面刷新的问题
前端·elementui
dancing99935 分钟前
cocos3.X的oops框架oops-plugin-excel-to-json改进兼容多表单导出功能
前端·javascript·typescript·游戏程序
HarderCoder1 小时前
学习React的一些知识
react.js
后海 0_o1 小时前
2025前端微服务 - 无界 的实战应用
前端·微服务·架构
Scabbards_1 小时前
CPT304-2425-S2-Software Engineering II
前端
小满zs1 小时前
Zustand 第二章(状态处理)
前端·react.js
程序猿小D1 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
萌萌哒草头将军1 小时前
🚀🚀🚀Prisma 发布无 Rust 引擎预览版,安装和使用更轻量;支持任何 ORM 连接引擎;支持自动备份...
前端·javascript·vue.js
狼性书生1 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件