搭建react-native項目框架之耗時代碼處理與Loading加載動畫
我們經(jīng)常需要執(zhí)行耗時較長的代碼。為了良好的用戶體驗,我們在異步處理耗時代碼時,采用Loading加載動畫的形式來等待處理。
這里參考了《React native Model組件的使用》。
1.在components下新建loading.js文件,如下
/** ?*?調(diào)用說明: ?*{this.Loading?=?r}}?hide?=?{true}?/>?//放在布局的最后即可 ?*?在需要顯示的地方調(diào)用this.Loading.show(); ?*?在需要隱藏的地方調(diào)用this.Loading.close(); ?*/ import?React,?{?Component?}?from?'react'; import?{ ????Platform, ????View, ????ActivityIndicator, ????Modal, }?from?'react-native'; import?PropTypes?from?'prop-types'; export?default?class?Loading?extends?Component?{ ????constructor(props)?{ ????????super(props); ????????this.state?=?{ ????????????modalVisible:?!this.props.hide, ????????} ????} ????close()?{ ????????if?(Platform.OS?===?'android')?{ ????????????setTimeout(()=>{ ????????????????this.setState({modalVisible:?false}); ????????????},1000) ????????}else?{ ????????????this.setState({modalVisible:?false}); ????????} ????} ????show()?{ ????????this.setState({modalVisible:?true}); ????} ????render()?{ ????????if?(!this.state.modalVisible)?{ ????????????return?null ????????} ????????return?({}} ????????????>); ????} } Loading.PropTypes?=?{ ????hide:?PropTypes.bool.isRequired, };
2.在App.js中引入loading.js
import?Loading?from?'./components/loading';
在最外層的View中底部渲染Loading
????????????{/*{/*......*/} ????????????????{/**/} ????????????????{/**/}{this.Loading?=?r}}?hide?=?{true}?/>
定義全局的方法
let?self;?//將App組件中的this賦給全局的self global.showLoading?=?false;?//所有子頁面均可直接調(diào)用global.showLoading()來展示Loading global.closeLoading?=?false;?//所有子頁面均可直接調(diào)用global.closeLoading()來關(guān)閉Loading
給全局方法賦值,使其可以在任何頁面調(diào)用
????componentDidMount()?{ ????????self?=?this; ????????global.showLoading?=?function()?{ ????????????self.Loading.show(); ????????}; ????????global.closeLoading?=?function()?{ ????????????self.Loading.close(); ????????}; ????}
調(diào)用Loading
????_showLoading()?{ ????????global.showLoading(); ????????setTimeout(()=>{ ????????????global.closeLoading(); ????????},500) ????}
this._showLoading();