如何使用 React Native 在屏幕中间显示加载进度或微调器?

How to show loading progress or spinner in the middle of the screen with React Native?

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

我能够自己解决所有问题,但这是个例外。 我将加载另一个带有底部选项卡导航器的屏幕。

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

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

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

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>
        )
    }
}

因此,当您必须加载 API 或其他内容并且收到 api 的响应时,您可以显示 Spinner 假设,您可以将微调器加载值设置为 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>
        )
    }
}

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

  1. 您可以使用 React Native Activity 指标 -> View
  2. 您可以使用覆盖库 -> react-native-loading-spinner-overlay -> View GitHub
  3. 如果你喜欢像 facebook / instagram 这样加载 -> 然后使用 react-native-easy-content-loader -> View GitHub

假设您使用的是 React Native Activity 指标:

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。

我已经创建了我的自定义加载程序组件。使用它,您可以显示内置的 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} />

你必须使用 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;