【问题标题】:How to show loading progress or spinner in the middle of the screen with React Native?如何使用 React Native 在屏幕中间显示加载进度或微调器?
【发布时间】:2020-05-14 11:30:08
【问题描述】:

我正在开发 React Native 应用程序。

我能够自己解决所有问题,但这是个例外。 我将使用底部标签导航器加载另一个屏幕。

例如,用户登录应用程序后,它应该显示主屏幕,其中包含许多图片和许多样式表效果、图标。因此,在登录确认后(我的意思是在登录确认警报后),几秒钟后会出现主屏幕。

所以我想在登录屏幕中显示一些微调器,同时在后台加载主主屏幕,当它准备好显示时,擦除微调器并显示主主屏幕。 我该怎么做?

我的底部标签导航器只是使用createBottomTabNavigator() 方法创建的。

【问题讨论】:

    标签: react-native animation loading react-navigation-bottom-tab


    【解决方案1】:

    我已经创建了我的自定义加载器组件。使用它,您可以显示内置的 ActivityIndi​​cator 或您的自定义 gif 加载器图像与覆盖。

    Loader.js

    import React, { Component } from 'react';
    import {
      StyleSheet,
      View,
      Modal,
      Image,
      ActivityIndicator
    } from 'react-native';
    
    class Loader extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isLoading: this.props.isLoading
        }
      }
    
      static getDerivedStateFromProps(nextProps) {
        return {
          isLoading: nextProps.isLoading
        };
      }
    
      render() {
        return (
          <Modal
            transparent={true}
            animationType={'none'}
            visible={this.state.isLoading}
            style={{ zIndex: 1100 }}
            onRequestClose={() => { }}>
            <View style={styles.modalBackground}>
              <View style={styles.activityIndicatorWrapper}>
                <ActivityIndicator animating={this.state.isLoading} color="black" />
                
                {/* If you want to image set source here */}
                {/* <Image
                  source={require('../assets/images/loader.gif')}
                  style={{ height: 80, width: 80 }}
                  resizeMode="contain"
                  resizeMethod="resize"
                /> */}
              </View>
            </View>
          </Modal>
        )
      }
    }
    
    const styles = StyleSheet.create({
      modalBackground: {
        flex: 1,
        alignItems: 'center',
        flexDirection: 'column',
        justifyContent: 'space-around',
        backgroundColor: '#rgba(0, 0, 0, 0.5)',
        zIndex: 1000
      },
      activityIndicatorWrapper: {
        backgroundColor: '#FFFFFF',
        height: 100,
        width: 100,
        borderRadius: 10,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-around'
      }
    });
    
    export default Loader
    

    现在您可以在必须显示加载指示器时使用它,如下所示:

    <Loader isLoading={this.state.isLoading} />
    

    【讨论】:

      【解决方案2】:

      所以在你的情况下,你可以做几件事

      1. 你可以使用 React Native Activity Indicator -> View
      2. 你可以使用 Overlay Library -> react-native-loading-spinner-overlay -> View GitHub
      3. 如果你喜欢像 facebook/instagram 那样加载 -> 然后使用 react-native-easy-content-loader -> View GitHub

      假设你正在使用 React Native Activity Indicator:

      import { ActivityIndicator } from "react-native";
      
      export default class HomeScreen extends Component {
        constructor(props) {
          super(props);
          this.state = {
            isLoading: true
          };
        }
      
        //Get Home Screen Data API Action
        componentDidMount() {
          this.loadAPI(); // Call home screen get data API function
        }
      
        //Login API Function
        loadAPI = () => {
          this.setState({ isLoading: true }); // Once You Call the API Action loading will be true
          fetch(API_URL, {
            method: "POST",
            headers: {
              "Content-Type": "application/json"
            }
          })
            .then(response => response.json())
            .then(responseText => {
              // You can do anything accroding to your API response
              this.setState({ isLoading: false }); // After getting response make loading to false
            })
            .catch(error => {});
        };
      
        render() {
          return (
            <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
              {this.state.isLoading && <ActivityIndicator color={"#fff"} />}
            </View>
          );
        }
      }
      
      • 如果您想在加载完成之前隐藏所有视图,就像图像一样,那么您可以使用自定义库而不是 Activity Indicator。

      【讨论】:

      【解决方案3】:

      你必须使用ActivityIndicator你必须在从服务器获取数据之前加载这个活动指示器,你必须检查下面的代码希望你能理解

          import React, {useEffect, useState} from 'react';
      import {ActivityIndicator, View, Dimensions} from 'react-native';
      import HomeScreen from './Home';
      
      const DataViewer = () => {
        const [data, setData] = useState([]);
        const {height, width} = Dimensions.get('window');
        useEffect(() => {
          fetch('http://example.com/movies.json')
            .then(response => {
              return response.json();
            })
            .then(myJson => {
              setData(myJson);
            });
        });
      
        return data.length > 0 ? (
          <HomeScreen data={data} />
        ) : (
          <View
            style={{justifyContent: 'center', alignItems: 'center', height, width}}>
            <ActivityIndicator size="large" color="#0000ff" />
          </View>
        );
      };
      
      export default DataViewer;
      

      【讨论】:

        【解决方案4】:

        所以当你必须加载 API 或其他东西时,你可以显示 Spinner,当你得到 api 的响应时,你可以将微调器加载值设置为 false。

        例如:

        import {View, ActivityIndicator } from 'react-native';
        
        export default class MainScreen extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    spinner : true
                }
            }
        
        componentDidMount(){
        this.loadApi();
        }
        
        loadApi = async() => {
        let result = axios.get('url').then((data) =>{
        this.setState({spinner:false});
        }
        ).catch((err) => this.setState({spinner:false})
        }
        
            render() {
                return (
                <View style={{flex : 1, justifyContent: 'center', alignItems: 'center',}}>
                {
                  this.state.spinner? <ActivityIndicator  color={'#fff'} />:<View><Text>Data loaded</Text></View>
        
                }
                </View>
                )
            }
        }
        

        【讨论】:

          【解决方案5】:

          import { ActivityIndicator } from 'react-native';
          
          export default class LoginScreen extends Component {
              constructor(props) {
                  super(props);
                  this.state = {
                      spinner : true
                  }
              }
              render() {
                  return (
                  <View style={{flex : 1, justifyContent: 'center', alignItems: 'center',}}>
                  {
                    this.state.spinner &&
                    <ActivityIndicator  color={'#fff'} />
                  }
                  </View>
                  )
              }
          }

          【讨论】:

          • 感谢您的回答。但我想知道的是如何设置那些this.state.spinner。什么时候必须设置为真,什么时候设置为假?
          猜你喜欢
          • 2020-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-11
          • 2022-12-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多