添加啓動頁可以使用react-native-splash-screen庫,通過它可以控制啓動頁的顯示和隱藏。
安裝
// react-native 6.0以上版本不用手動link
yarn add react-native-splash-screen
安卓配置
在MainActivity.java文件下添加以下代碼:
...
import android.os.Bundle;
import org.devio.rn.splashscreen.SplashScreen;
...
public class MainActivity extends ReactActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this); //add
super.onCreate(savedInstanceState);
}
}
然後在android/app/src/main/res/layout文件夾下創建啓動頁的XML文件launch_screen.xml並添加如下代碼:
<?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="@mipmap/launch_screen"> //該路徑爲後面設置的啓動圖片位置
</LinearLayout>
接着在android/app/src/main/res文件夾下創建mipmap文件夾(與上面background對應的地址一致),然後放入對應分辨率下的圖片。
爲防止白屏,還應做如下操作:
在android/app/src/main/res/values/styles.xml加入代碼:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:textColor">#000000</item>
<item name="android:windowIsTranslucent">true</item> // 用於設置透明白背景
</style>
</resources>
react-native 配置
在需要關閉啓動頁的js文件中引入import SplashScreen from ‘react-native-splash-screen’,然後在關閉處添加代碼SplashScreen.hide
componentDidMount(){
...
//2秒後關閉啓動頁
setTimeout(()=>{SplashScreen.hide()}, 2000, )
};
啓動頁就算完成了~