微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

React Native如何消除启动时白屏

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

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

白屏的原因

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

解决的常见方案:

  1. 启动图结束后通过原生代码加载一张全屏占位图片,跟启动图一样的图片,混淆视听“欺骗用户”。
  2. JS解释完毕后通知原生可以移除占位图
  3. 收到 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐