react-native-splash-screen 对此有很好的实现。
安装并链接原生依赖项后,您可以控制何时在原生代码中显示启动画面:
安卓:
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
SplashScreen.show(this); // here
super.onCreate(savedInstanceState);
}
// ...other code
}
iOS:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// ...other code
[RNSplashScreen show]; // here
// or
//[RNSplashScreen showSplash:@"LaunchScreen" inRootView:rootView];
return YES;
}
然后在您的 React 代码中,您可以控制何时隐藏启动画面
反应组件:
componentDidMount() {
// do stuff while splash screen is shown
// After having done stuff (such as async tasks) hide the splash screen
SplashScreen.hide();
}
React Hooks(组件加载后隐藏):
React.useEffect(() => {
SplashScreen.hide();
}, []);
React Hooks(超时后隐藏):
const [hideSplash, setHideSplash] = React.useState(false);
React.useEffect(() => {
setTimeout(() => {
setHideSplash(true);
}, 1000); // amount of time the splash is shown from the time component is rendered
}, []);
React.useEffect(() => {
hideSplash && SplashScreen.hide();
}, [hideSplash]);
// ...