app闪屏是一个常见的需求,今天我们来说一下使用 react-native-splash-screen组件实现闪屏功能。
一、具体使用
(一)安装
- 使用安装命令
npm i react-native-splash-screen --save
进行安装 - 使用命令
react-native link react-native-splash-screen
link
注:我安装的版本是3.0.0,最新版用法请查看react-native-splash-screen
iOS
- 在Xcode中点击Library,选择Add Files to [your project's name],选择node_modules ➜ react-native-splash-screen 添加SplashScreen.xcodeproj
- 在Build PhasesLink ➜ Binary With Libraries中添加libSplashScreen.a
- 在Build Settings ➜ Search Paths ➜ Header Search Paths中添加
$(SRCROOT)/../node_modules/react-native-splash-screen/ios
Android
- 找到android/settings.gradle文件,添加如下代码:
include ':react-native-splash-screen'
project(':react-native-splash-screen').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-splash-screen/android')
- 在android/app/build.gradle文件中,添加如下代码:
...
dependencies {
...
compile project(':react-native-splash-screen')
}
- 在 MainApplication.java中添加如下代码:
// 3.0.1以下版本
import com.cboy.rn.splashscreen.SplashScreenReactPackage;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new SplashScreenReactPackage() // 这里添加
);
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
}
(二)使用
iOS
- 在AppDelegate.m中添加:
#import "AppDelegate.h"
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>
#import "SplashScreen.h" //这里添加
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...其他代码
[SplashScreen show]; // 这里添加
return YES;
}
@end
- 将闪屏图片放入LaunchScreen.xib
Android
- 在MainActivity.java中添加:
import com.cboy.rn.splashscreen.SplashScreen; //这里添加
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this); // 这里添加
super.onCreate(savedInstanceState);
}
// ...其他代码
}
- 在app/src/main/res/layout中新建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="@drawable/splash">
</LinearLayout>
- 将闪屏图片放入以下目录:
- mipmap-hdpi
- mipmap-mdpi
- mipmap-xhdpi
- mipmap-xxhdpi
- mipmap-xxxhdpi
最后,在splash.js中添加如下代码:
import SplashScreen from 'react-native-splash-screen'
export default class WelcomePage extends Component {
componentDidMount() {
SplashScreen.hide();
}
}