当前位置:首页 > 芯闻号 > 充电吧
[导读]我们经常需要执行耗时较长的代码。为了良好的用户体验,我们在异步处理耗时代码时,采用Loading加载动画的形式来等待处理。这里参考了《React native Model组件的使用》。1.在compo

我们经常需要执行耗时较长的代码。为了良好的用户体验,我们在异步处理耗时代码时,采用Loading加载动画的形式来等待处理。

这里参考了《React native Model组件的使用》。


1.在components下新建loading.js文件,如下

/**
 * 调用说明:
 *{this.Loading = r}} hide = {true} /> //放在布局的最后即可
 * 在需要显示的地方调用this.Loading.show();
 * 在需要隐藏的地方调用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; //所有子页面均可直接调用global.showLoading()来展示Loading
global.closeLoading = false; //所有子页面均可直接调用global.closeLoading()来关闭Loading

给全局方法赋值,使其可以在任何页面调用

    componentDidMount() {
        self = this;
        global.showLoading = function() {
            self.Loading.show();
        };
        global.closeLoading = function() {
            self.Loading.close();
        };
    }

调用Loading

    _showLoading() {
        global.showLoading();
        setTimeout(()=>{
            global.closeLoading();
        },500)
    }
this._showLoading();


本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭