在做全局loading时,出现的问题,使用 antd-mobile 中 Icon 组件,导致 loading组件无法关闭的问题,
loading.jsx
import React from ‘react‘; import ReactDOM from ‘react-dom‘; import { Icon } from ‘antd-mobile‘; import ‘./style.less‘; class Loading { static animating = false open () { Loading.animating = document.getElementById(‘loading‘) if (Loading.animating) return; const dom = document.createElement(‘div‘) dom.setAttribute(‘id‘, ‘loading‘) document.body.appendChild(dom) ReactDOM.render( <div className=‘load‘ id=‘load‘> <Icon type=‘loading‘ /> </div>, dom ) } close () { console.log(document.getElementById(‘loading‘)) document.body.removeChild(document.getElementById(‘loading‘)) } } export default new Loading();
调用顺序
Loading.open()
setTimeout(() => {
Loading.close()
}, 1000);
打印出的信息
出现 问题:
Loading.close() 方法执行时,无法清除元素,即 document.body.removeChild(document.getElementById(‘loading‘)) 方法无效
解决
由 Icon 组件 改为 ActivityIndicator 组件, console.log(document.getElementById(‘loading‘)); 即可获得到 正常 的 div元素,即 可通过removeChild 清除
import React from ‘react‘; import ReactDOM from ‘react-dom‘; import { ActivityIndicator } from ‘antd-mobile‘; import ‘./style.less‘; class Loading { static animating = false open () { Loading.animating = document.getElementById(‘loading‘) if (Loading.animating) return; const dom = document.createElement(‘div‘) dom.setAttribute(‘id‘, ‘loading‘) document.body.appendChild(dom) ReactDOM.render( <div className=‘load‘ id=‘load‘> <ActivityIndicator size="large" /> </div>, dom ) } close () { document.body.removeChild(document.getElementById(‘loading‘)) } } export default new Loading();
原因
Icon 组件实际为一个 SVG 标签,所以会获取到 symbol 标签