ReactNative 启动白屏解决方案 react-native-splash-screen

安装

1.添加
yarn add react-native-splash-screen
2.自动link
react-native link
或者
react-native link react-native-splash-screen

修改原生代码

Android:

通过以下更改更新MainActivity.java以使用react-native-splash-screen:

import android.os.Bundle; // here 
import com.facebook.react.ReactActivity;
// react-native-splash-screen >= 0.3.1 
import org.devio.rn.splashscreen.SplashScreen; // here 
// react-native-splash-screen < 0.3.1 
import com.cboy.rn.splashscreen.SplashScreen; // here 

public class MainActivity extends ReactActivity {
   @Override
    protected void onCreate(Bundle savedInstanceState) {
        SplashScreen.show(this);  // here 
        super.onCreate(savedInstanceState);
    }
    // ...other code 
}
iOS:

使用以下添加内容更新AppDelegate.m:

#import "AppDelegate.h"

#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "SplashScreen.h"  // here

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // ...other code

    [SplashScreen show];  // here
    return YES;
}

@end

配置资源文件

Android还需要配置一些资源文件

在app / src / main / res / layout中创建一个名为launch_screen.xml的文件(如果不存在,则创建layout文件夹)。该文件的内容应如下所示:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/launch_screen">
</LinearLayout>
在app / src / main / res / drawable中创建一个名为launch_screen的图片文件(如果不存在,则创建drawable文件夹)。
通过创建launch_screen.png文件并将其放入适当的可绘制文件夹来自定义启动屏幕。Android会自动缩放drawable,因此您不一定需要为所有手机密度提供图像。您可以在以下文件夹中创建启动画面:
  • drawable-ldpi
  • drawable-mdpi
  • drawable-hdpi
  • drawable-xhdpi
  • drawable-xxhdpi
  • drawable-xxxhdpi
在app / src / main / res / values / color.xml中添加一个名为primary_dark的颜色:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary_dark">#000000</color>
</resources>
设置背景透明

如果不设置的,还是会有一小段时间白屏。
打开android / app / src / main / res / values / styles.xml并将<item name =“android:windowIsTranslucent”> true </ item>添加到文件中。它应该看起来像这样:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <!--设置透明背景-->
        <item name="android:windowIsTranslucent">true</item>
    </style>
</resources>

Android端结构图大致为:
项目结构图

JS端代码:

import SplashScreen from 'react-native-splash-screen'

export default class WelcomePage extends Component {

    componentDidMount() {
        // do stuff while splash screen is shown
        // After having done stuff (such as async tasks) hide the splash screen
        SplashScreen.hide();
    }
}

猜你喜欢

转载自blog.csdn.net/u011272795/article/details/80857683