react 方法組件構造 Loading 的使用

這裏的方法組件並不是 指的 函數組件,而是可以像方法一樣使用的組件

就好像是 ant-design 裏的 message.success() 一樣使用。

上代碼

loading.css

      .loading-container{
        width: 100%;
        height: 100%;
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,0.5);
        z-index:999;
      }
      .img{
        position: absolute;
        left: 50%;
        top: 50%;
        transform: -50% -50%;
      }

loading.js

function Loading(props) {
   console.log(props)
   return <div className="loading-container">
             <img className="img" src="./loading.gif"/>
           </div>
}
// js 中萬物皆對象,function 自然也可以作爲對象存儲 數據
Loading.show = function (props) {
   this.div = document.createElement('div');
   document.body.appendChild(this.div);

   ReactDOM.render(<Loading {...props}/>, this.div);
}
Loading.remove = function () {
   this.div && ReactDOM.unmountComponentAtNode(this.div); //從div中移除已掛載的Loading組件
   this.div && this.div.parentNode.removeChild(this.div); //移除掛載的容器
}
export default Loading;

調用的時候,可以直接導入,然後  

使用 Loading.show() 和 loading.remove() 去除這個loading 狀態,而不需要 一層一層地包裹,直接寫進方法裏就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章