RN code push自定义弹框

最近在弄react native的code push热更新问题。开始是用的后台默默更新配置。由于微软服务器速度问题,经常遇到用户一直在下载中问题。而用户也不知道代码需要更新才能使用新功能,影响了正常业务流程。而目前公司也无力搭建自己的服务器和dns设置。所以比较快速的方案就是,前端自定义热更新弹框,在需要更新代码的情况下禁止用户向下操作。

ok,废话少说,直接上代码:

这是构建一个弹框,强制文案提示和非强制文案提示弹框。

/**
 * Created by susie on 2018/9/20.
 */
import React, { Component } from ‘react‘;
import {View, Text, StyleSheet, Modal, TouchableOpacity, Image , Dimensions , Alert} from ‘react-native‘
import CodePush from "react-native-code-push"
import Progress from ‘./CusProgressBar‘;
import color from ‘../../styles/theme‘;
import {showLoadingImg,hideLoadingImg,px2pt} from ‘../../utils/util‘;
import Global from "../../constants/global";

let SCREEN_WIDTH = Dimensions.get(‘window‘).width;//宽
let SCREEN_HEIGHT = Dimensions.get(‘window‘).height;//高

let codePushOptions = {
    checkFrequency : CodePush.CheckFrequency.ON_APP_START,
    installMode: CodePush.InstallMode.IMMEDIATE
}

 class CodePushModal extends Component {

    constructor(props) {
        super(props)
        this.currProgress = 0.0
        this.syncMessage = ‘‘
        this.state = {
            modalVisible: false, //是否有更新
            isMandatory: false, //是否为强制更新
            immediateUpdate: false, //是否在更新中
            updateInfo: {}
        }
    }

    codePushStatusDidChange(syncStatus) {
        if (this.state.immediateUpdate) {
            switch(syncStatus) {
                case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
                    this.syncMessage = ‘Checking for update‘
                    break;
                case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
                    this.syncMessage = ‘Downloading package‘
                    break;
                case CodePush.SyncStatus.AWAITING_USER_ACTION:
                    this.syncMessage = ‘Awaiting user action‘
                    break;
                case CodePush.SyncStatus.INSTALLING_UPDATE:
                    this.syncMessage = ‘Installing update‘
                    break;
                case CodePush.SyncStatus.UP_TO_DATE:
                    this.syncMessage = ‘App up to date.‘
                    break;
                case CodePush.SyncStatus.UPDATE_IGNORED:
                    this.syncMessage = ‘Update cancelled by user‘
                    break;
                case CodePush.SyncStatus.UPDATE_INSTALLED:
                    this.syncMessage = ‘Update installed and will be applied on restart.‘
                    break;
                case CodePush.SyncStatus.UNKNOWN_ERROR:
                    this.syncMessage = ‘An unknown error occurred‘
                    //Toast.showError(‘更新出错,请重启应用!‘)
                    this.setState({modalVisible: false})
                    CodePush.allowRestart();
                    break;
            }
        }
    }

    codePushDownloadDidProgress(progress) {
        var self = this;
        if(self.state.immediateUpdate){
            self.currProgress = parseFloat(progress.receivedBytes / progress.totalBytes).toFixed(2);
            if(self.currProgress >= 1) {
                self.setState({modalVisible: false})
            } else if(self.refs.progressBar) {
                self.refs.progressBar.progress = self.currProgress;
                self.refs.progressBar.buffer = self.currProgress;
            }
        }
    }

     syncImmediate() {
        CodePush.checkForUpdate().then((update) => {
            Global.isCheckCodePush = false;
            hideLoadingImg();
            if (!update) {
                CodePush.allowRestart();
            } else {
                this.setState({modalVisible: true, updateInfo: update, isMandatory: update.isMandatory})
            }
        }).catch(function () {
            Global.isCheckCodePush = false;
            CodePush.allowRestart();
        })
    }

    componentWillMount() {
        Global.isCheckCodePush = true;
        showLoadingImg();
        CodePush.disallowRestart()
        this.syncImmediate()
    }

    componentDidMount() {
        //CodePush.allowRestart()
    }

    _immediateUpdateNew() {
        this.setState({immediateUpdate: true});
        let self = this;
        var timer = setTimeout(function () {
            CodePush.sync(
                {
                    updateDialog: {},
                    installMode: CodePush.InstallMode.IMMEDIATE},
                self.codePushStatusDidChange.bind(self),
                self.codePushDownloadDidProgress.bind(self)
            )
            clearTimeout(timer);
            CodePush.allowRestart();
        },10);
    }

    render() {
        return (
            <View style={styles.container}>
            <Modal
                animationType={"none"}
                transparent={true}
                onRequestClose={() => {}}
                visible={this.state.modalVisible}
            >
                <View style={styles.modal}>
                    <View style={styles.modalContainer}>
                        {
                            !this.state.immediateUpdate ?
                                <View>
                                    <View style={styles.modalContent}>
                                        <View>
                                            <Text style={styles.modalTitle}>页面升级</Text>
                                        </View>
                                        <View style={styles.updateDes}>
                                            <Text style={styles.updateDesText}>升级内容:</Text>
                                            <Text style={styles.updateDesText}>{this.state.updateInfo.description}</Text>
                                        </View>
                                        <View style={styles.updateTip}>
                                            <Text style={styles.updateTipText}>本升级非APP更新,wifi环境下30s内即可完成</Text>
                                        </View>
                                        {
                                            !this.state.isMandatory ?
                                                <View style={styles.updateBtns}>
                                                    <TouchableOpacity
                                                        onPress={() => this.setState({modalVisible: false})}>
                                                        <View style={[styles.btnRight,styles.btnLeft]}>
                                                            <Text style={{fontSize: 16, color: ‘#989898‘}}>残忍拒绝</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                    <TouchableOpacity
                                                        style={styles.btnRight}
                                                        onPress={() => this._immediateUpdateNew()}
                                                    >
                                                        <View style={styles.btnRightText}>
                                                            <Text style={{fontSize: 16, color: color.theme}}>立即升级</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                </View> :
                                                <View style={styles.updateBtns}>
                                                    <TouchableOpacity
                                                        style={[styles.btnRight,styles.onlyBtn]}
                                                        onPress={() => this._immediateUpdateNew()}
                                                    >
                                                        <View style={[styles.btnRightText,{marginHorizontal: 40}]}>
                                                            <Text style={{fontSize: 16, color: color.theme, letterSpacing:1}}>立即升级</Text>
                                                        </View>
                                                    </TouchableOpacity>
                                                </View>
                                        }
                                    </View>
                                </View> : <View style={styles.modalContent}>
                                        <View>
                                            <Text style={styles.modalTitle}>页面升级中</Text>
                                        </View>
                                        <View style={{ paddingVertical: 20, alignItems: ‘center‘}}>
                                            <Progress
                                                ref="progressBar"
                                                progressColor={‘#89C0FF‘}
                                                style={{
                                                    marginTop: 20,
                                                    width: SCREEN_WIDTH - 80,
                                                    marginLeft:10,
                                                    marginRight:10
                                                }}
                                            />
                                            <View style={styles.updateTip}>
                                                <Text style={styles.updateTipText}>本升级非APP更新,wifi环境下30s内即可完成</Text>
                                            </View>
                                        </View>
                                </View>

                        }
                    </View>
                </View>
            </Modal>
            </View>
        );
    }
}
let modalW = SCREEN_WIDTH - 40;
const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: ‘center‘,
        alignItems: ‘center‘
    },
    modal: {
        height: SCREEN_HEIGHT,
        width: SCREEN_WIDTH,
        alignItems: ‘center‘,
        justifyContent: ‘center‘,
        backgroundColor: ‘rgba(0,0,0,0.3)‘
    },
    modalContainer: {
        marginHorizontal: px2pt(120),
        borderBottomLeftRadius: px2pt(20),
        borderBottomRightRadius: px2pt(20),
    },
    modalContent:{
        backgroundColor: ‘#FFF‘,
        borderRadius:5,
        width: modalW
    },
    modalTitle:{
        marginTop:px2pt(70),
        fontSize:px2pt(36),
        color:color.gray3,
        textAlign:‘center‘,
        width:‘100%‘
    },
    modalTips:{
        fontSize:px2pt(28),
        color:color.darkOrange,
        textAlign:‘center‘,
        marginBottom:px2pt(10)
    },
    updateDes:{
        marginLeft:px2pt(40),
        marginRight:px2pt(40),
        marginTop:px2pt(30)
    },
    updateDesText:{
        fontSize:px2pt(32),
        color: color.gray6,
        lineHeight:px2pt(44)
    },
    updateTip:{
        alignItems: ‘center‘,
        marginTop: px2pt(40)
    },
    updateTipText:{
        fontSize: px2pt(28),
        color: color.gray6
    },
    updateBtns:{
        flexDirection: ‘row‘,
        height: px2pt(100),
        alignItems: ‘center‘,
        marginTop: px2pt(40),
        borderTopColor: ‘#E6E6E6‘,
        borderTopWidth: 1
    },
    btnLeft:{
        borderRightColor: ‘#E6E6E6‘,
        borderRightWidth: 1
    },
    btnRight:{
        flexDirection: ‘row‘,
        alignItems: ‘center‘,
        width: modalW / 2,
        height:px2pt(100),
        justifyContent: ‘center‘
    },
    btnRightText:{
        flex: 1,
        height:px2pt(80),
        alignItems: ‘center‘,
        justifyContent: ‘center‘
    },
    onlyBtn:{
        width: modalW
    }
})

export default CodePush(codePushOptions)(CodePushModal)

  其中,注意installMode 的设置问题,在初始化CodePush参数时,就要设置。否则在非强制更新下会出现 不立即刷新的问题。

然后是进度条展示处理:

/**
 * Created by susie on 2018/9/20.
 */
import React, {Component}from ‘react‘
import {View, StyleSheet, Animated, Easing,Text}from ‘react-native‘
import LinearGradient from ‘react-native-linear-gradient‘

import PropTypes from ‘prop-types‘

export default class CusProgressBar extends Component {

    static propTypes = {
        ...View.propTypes,
        // 当前进度
        progress: PropTypes.number,
        // second progress进度
        buffer: PropTypes.number,
        // 进度条颜色
        progressColor: PropTypes.string,
        // 进度动画时长
        progressAniDuration: PropTypes.number,
        // buffer动画时长
        bufferAniDuration: PropTypes.number
    }

    static defaultProps = {
        // 进度条颜色
        progressColor: ‘white‘,
        // 进度条动画时长
        progressAniDuration: 100,
        // buffer进度条动画时长
        bufferAniDuration: 100
    }

    constructor(props) {
        super(props)
        this._progressAni = new Animated.Value(0)
        this._bufferAni = new Animated.Value(0)
    }

    componentWillReceiveProps(nextProps) {
        this._progress = nextProps.progress
        this._buffer = nextProps.buffer
    }

    componentWillMount() {
        this._progress = this.props.progress
        this._buffer = this.props.buffer
    }

    render() {
        return (
            <View
                style={[styles.container,this.props.style]}
                onLayout={this._onLayout.bind(this)}>
                <LinearGradient colors={[‘#daddff‘, ‘#d3eeff‘]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{position:‘absolute‘,borderRadius:10,width:‘100%‘,height:‘100%‘}}></LinearGradient>
                <Animated.View
                    ref="progress"
                    style={{
                        position:‘absolute‘,
                        width: this._progressAni,
                        borderRadius:10
                    }}>
                    <LinearGradient colors={[‘#4669ff‘, ‘#3eefff‘]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={{borderRadius:10,width:‘100%‘,height:‘100%‘}}></LinearGradient>
                </Animated.View>
                <Animated.Image
                    ref="buffer"
                    style={{
                        position:‘absolute‘,
                        left: this._bufferAni,
                        marginLeft:0,
                        top : -3,
                        width:35
                    }}  source={require(‘../../styles/images/huojian.png‘)}  />
            </View>
        )
    }

    _onLayout({nativeEvent: {layout:{width, height}}}) {
        // 防止多次调用,当第一次获取后,后面就不再去获取了
        if (width > 0 && this.totalWidth !== width) {
            // 获取progress控件引用
            let progress = this._getProgress()
            // 获取buffer控件引用
            let buffer = this._getBuffer()
            // 获取父布局宽度
            this.totalWidth = width
            //给progress控件设置高度
            progress.setNativeProps({
                style: {
                    height: height
                }
            })

            // 给buffer控件设置高度
            buffer.setNativeProps({
                style: {
                    height: height+6
                }
            })
        }
    }

    _startAniProgress(progress) {
        if (this._progress >= 0 && this.totalWidth !== 0) {
            Animated.timing(this._progressAni, {
                toValue: progress * this.totalWidth,
                duration: this.props.progressAniDuration,
                easing: Easing.linear
            }).start()
        }
    }

    _startAniBuffer(buffer) {
        if (this._buffer >= 0 && this.totalWidth !== 0) {
            Animated.timing(this._bufferAni, {
                toValue: buffer * this.totalWidth,
                duration: this.props.bufferAniDuration,
            }).start()
        }
    }

    _getProgress() {
        if (typeof this.refs.progress.refs.node !== ‘undefined‘) {
            return this.refs.progress.refs.node
        }
        return this.refs.progress._component
    }

    _getBuffer() {
        if (typeof this.refs.buffer.refs.node !== ‘undefined‘) {
            return this.refs.buffer.refs.node;
        }
        return this.refs.buffer._component;
    }
}

Object.defineProperty(CusProgressBar.prototype, ‘progress‘, {
    set(value){
        if (value >= 0 && this._progress !== value) {
            this._progress = value;
            this._startAniProgress(value);
        }
    },
    get() {
        return this._progress;
    },
    enumerable: true,
})

Object.defineProperty(CusProgressBar.prototype, ‘buffer‘, {
    set(value){
        if (value >= 0 && this._buffer !== value) {
            this._buffer = value;
            this._startAniBuffer(value);
        }
    },
    get() {
        return this._buffer;
    },
    enumerable: true,
})

const styles = StyleSheet.create({
    container: {
        height: 12
    }
})

 以上就完成了自定义 code push弹框的自定义展示。

原文地址:https://www.cnblogs.com/susie-note/p/9791212.html

时间: 2024-10-07 12:45:59

RN code push自定义弹框的相关文章

js组件--自定义弹框

javascript自定义弹框 性能太差,有很大的改善空间 1 <!doctype html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <!--<link href="styles/reset.css" type="text/css&

简单的自定义弹框

作为初学者,很多人都是用的系统自带的弹框,非常的简单,完全不能满足用户的交互,所以这里,我们需要自定义一个弹框,把输入框.图片.按钮等添加到弹框里面.为了避免重复冗余的代码,参考了别人的代码,自己做了一个自定义弹框,可以在项目中使用到.给大家一个思路. 这是代码的接口定义,只需要调用一行代码就可以弹出一个自定义的视图啦.还会添加一些动画效果,让弹框弹出跟消失更美观. + (void)showPromptBoxWithCustomView:(UIView *)customView; + (void

Windows Phone开发学习笔记(1)---------自定义弹框

Windows Phone开发学习笔记(1) ---------自定义弹框 在WP中自定义弹框是可以通过Popup类实现的. Popup的语法为: [ContentPropertyAttribute("Child")] [LocalizabilityAttribute(LocalizationCategory.None)] public class Popup : FrameworkElement, IAddChild; 这是Popup使用的小列子 Popup codePopup =

自定义弹框加载方式

- (void)show { if ([UIApplication sharedApplication].keyWindow.rootViewController.navigationController) { [[UIApplication sharedApplication].keyWindow.rootViewController.navigationController.view addSubview:self]; }else{ [[UIApplication sharedApplica

自定义弹框

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv=&q

swift 自定义弹框

// //  ViewController.swift //  animationAlert // //  Created by su on 15/12/9. //  Copyright © 2015年 tian. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //灰色的遮挡板 let o

html自定义弹框

一.要实现的功能 1.弹框弹出时有遮罩 2.弹框内的文字过多时右侧有滚动条 3.根据执行结果变更弹框title的样式 二.具体实现 思路:定义一个有宽高的div,默认隐藏,当要显示时,设置为display=block来显示 1.定义div布局,一个遮罩层:一个弹框(弹框中有标题和内容两部分) <div id="dialogmask" class="dialogmask opacity"></div> <div id="dial

自定义弹框,点击提示框外空白区域,让弹框消失

tip: self.mainView  是提示框的全屏背景.一般是透明的黑色 self.bgImg   添加提示内容的主要view 方法一:正常情况下,各个页面都有touchesBegan:withEvent事件的触发.使用该方法 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; // 计算搜索框范围 CGPoint touchPoint

android之自定义弹框

step1 创建窗体 final AlertDialog dialog =new Builder(this).create(); step2 获取View View viewDialog =View.inflate(this, R.layout.userinfo_dialog_edit, null); final EditText txtUserName=(EditText)viewDialog.findViewById(R.id.txtUserName); final EditText txt