Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hiển thị Loading Indicator (ActivityIndicator) trong React Native


ActivityIndicator là component tích hợp sẵn của React Native để hiển thị vòng quay tải (spinner) khi ứng dụng đang xử lý tác vụ mất thời gian (gọi API, tải dữ liệu, v.v.).

Import

import { ActivityIndicator, View, StyleSheet } from 'react-native';

Cú pháp cơ bản

<ActivityIndicator 
  animating={true} 
  color="#bc2b78" 
  size="large" 
  style={styles.indicator} 
/>

Các props chính

PropKiểuMô tả
animatingbooleantrue: hiển thị & quay, false: ẩn & dừng.
colorstringMàu của spinner.
sizeenum'small' (20px) hoặc 'large' (36px - mặc định).
hidesWhenStoppedbooleanTự ẩn khi animating={false} (mặc định: true).

Ví dụ cơ bản: Tự ẩn sau 60 giây

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

class ActivityIndicatorExample extends Component {
  state = { animating: true };

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

  componentDidMount = () => this.closeActivityIndicator();

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

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    marginTop: 70,
  },
  activityIndicator: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    height: 80,
  },
});

export default ActivityIndicatorExample;

Ví dụ thực tế: Loading khi fetch API

import React, { useState, useEffect } from 'react';
import { ActivityIndicator, View, Text, StyleSheet } from 'react-native';

const DataFetching = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/posts/1')
      .then(res => res.json())
      .then(json => {
        setData(json);
        setLoading(false);
      })
      .catch(err => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return (
      
        
        Đang tải dữ liệu...
      
    );
  }

  if (error) return Lỗi: {error};

  return (
    
      {data.title}
      {data.body}
    
  );
};

const styles = StyleSheet.create({
  centered: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  loadingText: { marginTop: 10, fontSize: 16 },
  container: { flex: 1, padding: 20 },
  title: { fontSize: 20, fontWeight: 'bold', marginBottom: 10 },
  error: { color: 'red', textAlign: 'center', marginTop: 20 },
});

export default DataFetching;

Mẹo hay

  • Bọc ActivityIndicator trong View có flex: 1 và justifyContent: 'center' để căn giữa màn hình.
  • Dùng react-native-paper nếu muốn ProgressBar hoặc Snackbar loading đẹp hơn.
  • Trên Android, color mặc định là xám, nên chỉ định rõ màu thương hiệu.