React实现全局Loading

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);
}
注意:css样式放到全局样式文件中。

页面代码

使用了antd的Spin组件


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,保证组件风格统一性。

使用ReactDOM.render是因为原生dom节点是没办法直接使用jsx组件的,所以需要ReactDOM.render。

注意点

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

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

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

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值