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为啥可以滑动,是因为自己项目问题)。

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

相关推荐
耀耀切克闹灬几秒前
WEB前端基础知识梳理(四)
前端
anyup11 分钟前
🔥🔥 10 天 Star 破百!uView Pro 文档也开源啦:完全免费、无广告、高效上手
前端·vue.js·uni-app
Rasir16 分钟前
第七章:高级特性与项目优化
前端
春日野柚16 分钟前
前端打包优化分析
前端·webpack
yvvvy20 分钟前
DNS 解析全解析:从域名到 IP 的“桥梁”之旅
前端
柯南二号26 分钟前
【后端】SpringBoot中HttpServletRequest参数为啥不需要前端透传
前端·spring boot·后端
Dignity_呱34 分钟前
如何在不发版时,实现小程序的 AB 测试?
前端·面试·微信小程序
跟橙姐学代码1 小时前
学Python,先把这“三板斧”练到炉火纯青!(零基础也能看懂)
前端·python
Jimmy1 小时前
客户端存储 - IndexedDB
前端·javascript·indexeddb
滕本尊1 小时前
从业务到框架:Elpis 企业级应用的 NPM 包抽离实践
前端·全栈