当前位置: 移动技术网 > IT编程>开发语言>JavaScript > React Native如何消除启动时白屏的方法

React Native如何消除启动时白屏的方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

在rn 项目启动之后有一个短暂的白屏,调试阶段白屏的时间较长,大概3-5秒,打正式包后这个白屏时间会大大缩短,大多时候都是一闪而过,所以称之为“闪白”。

这里写图片描述

这里写图片描述

其实解决的方案也有很多,这里做一个简单的总结。

白屏的原因

在ios app 中有 启动图(launchimage),启动图结束后才会出现上述的闪白,这个过程是 js 解释的过程,js 解释完毕之前没有内容,所以才表现出白屏,那么解决的方法就是在启动图结束后,js 解释完成前做一些简单的处理。

解决的常见方案:

  • 启动图结束后通过原生代码加载一张全屏占位图片,跟启动图一样的图片,混淆视听“欺骗用户”。
  • js解释完毕后通知原生可以移除占位图
  • 收到 js 发来的可以移除占位图的通知,移除占位图

代码实现

新建一个splashscreen 文件用来接收 js 发来的”移除占位图”的消息。相关代码如下:

splashscreen.h

#import <foundation/foundation.h>
 #import "rctbridgemodule.h"
 @interface splashscreen : nsobject<rctbridgemodule>

 @end

splashscreen.m

#import "splashscreen.h"
 @implementation splashscreen

 rct_export_module();

 rct_export_method(close){
  [[nsnotificationcenter defaultcenter] postnotificationname:@"notification_close_splash_screen" object:nil];
 }
 @end

在appdelegate.m 加入以下代码:

@interface appdelegate ()
 {
  uiimageview *splashimage;
 }
 @end

 @implementation appdelegate

 - (bool)application:(uiapplication *)application didfinishlaunchingwithoptions:(nsdictionary *)launchoptions
 {
    [[nsnotificationcenter defaultcenter]addobserver:self selector:@selector(closesplashimage) name:"notification_close_splash_screen" object:nil];

   ...
   [self autosplashscreen];//写在 return yes 之前,其他代码之后
   return yes;
 }
 -(void)autosplashscreen {
  if (!splashimage) {
   splashimage = [[uiimageview alloc]initwithframe:[uiscreen mainscreen].bounds];
  }
  if (iphonescreen3p5) {
   [splashimage setimage:[uiimage imagenamed:@"launch4"]];
  }else if (iphonescreen4){
   [splashimage setimage:[uiimage imagenamed:@"launch5"]];
  }else if (iphonescreen4p7){
   [splashimage setimage:[uiimage imagenamed:@"launch6"]];
  }else if (iphonescreen5p5){
   [splashimage setimage:[uiimage imagenamed:@"launch7"]];
  }
  [self.window addsubview:splashimage];
 }
 -(void)closesplashimage {
    dispatch_sync(dispatch_get_main_queue(), ^{
     [uiview animatewithduration:0.5 animations:^{
      splashimage.alpha = 0;
     } completion:^(bool finished){
      [splashimage removefromsuperview];
     }];
    });
 }

在合适的时机选择移除占位图。js端代码:

if (platform.os === 'ios') {
   nativemodules.splashscreen.close();
 };

 更加详细的信息可以访问:https://github.com/crazycodeboy/react-native-splash-screen/blob/master/readme.zh.md

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网