React Native,用 Loading Indicator 和 setTimeout() 覆盖(覆盖)请求的页面以隐藏它

React Native, Cover (Overlay) the Requested Page with Loading Indicator and setTimeout() to Hide it

我有这段代码,它可以很好地显示覆盖请求页面 5 秒并隐藏以显示请求页面的内容,但是当加载程序指示器消失时,它的(红色)背景仍然存在,如何隐藏背景也? 它有两部分,第一部分用于创建加载指示器,以便在 5 秒后隐藏。 Expo.io 上的工作示例: Live Demo - 这是请求页面的代码:(请注意,必须从 /screens 调用)

import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Loader from './screens/Loader';

export default function App() {
return (
<View style={styles.container}>
<Loader /> //<--- I put the Loader here
  <Text style={styles.paragraph}>
    This is the requested page should be be covered by indicator background (Red color) <br/ >
    The Loader disappear after 5 sec.<br />
    But, its background still there!!
  </Text>
</View>
);
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

而 Loader.js 代码是:

import React, { Component } from 'react';
import { ActivityIndicator, View, Text, TouchableOpacity, StyleSheet } from 'react-native';

class Loader extends Component {
state = { animating: true }

closeActivityIndicator = () => setTimeout(() => this.setState({
animating: false }), 5000)

componentDidMount = () => this.closeActivityIndicator()
render() {
  const animating = this.state.animating
  return (
     <View style = {styles.container}>
        <ActivityIndicator
           animating = {animating}
           color = '#bc2b78'
           size = "large"
           style = {styles.activityIndicator}/>
     </View>
  )
  }
  }
 export default Loader
 const styles = StyleSheet.create ({
 container: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
  marginTop: 0,
  position: 'absolute',
  height: "100%",
  width: "100%",
  backgroundColor: 'red',
  opacity: 0.7
  },
  activityIndicator: {
  flex: 1,
  justifyContent: 'center',
  alignItems: 'center',
  }
  })

问题是您总是在渲染加载程序并且它始终可见,因此处理此问题的最简单方法是 return null 并在不需要时隐藏加载程序,如下所示。

   render() {
      const animating = this.state.animating;

      if(!this.state.animating)
        return null;

      return (
         <View style = {styles.container}>
            <ActivityIndicator
               animating = {animating}
               color = '#bc2b78'
               size = "large"
               style = {styles.activityIndicator}/>
         </View>
      )
   }