DIV CSS 佈局教程網

React Native 如何消除啟動時的白屏閃白問題
編輯:JavaScript技巧     

React Native 專案啟動後會出現一段短暫的白屏。除錯階段這段時間比較長,大約 3 到 5 秒;打包成正式版本後會大幅縮短,多數時候一閃而過,所以常被稱為「閃白」。

解法其實不少,這裡做一個簡單的整理。

白屏的成因

在 iOS App 中有一張啟動圖(LaunchImage),啟動圖消失之後才會出現上述閃白。這段過程其實是 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

以上就是這次的整理,希望對你的開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved