Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีแสดง Loading Indicator ใน React Native


Loading Indicator ใช้เมื่อต้องการบอกผู้ dùngว่าคำขอที่ทำบน UI จะใช้เวลาบ้าง เช่น เมื่อผู้ใช้กดปุ่มส่งฟอร์มหรือกดปุ่มค้นหาข้อมูล

React Native มีคอมโพเนนต์ ActivityIndicator ที่ให้วิธีการแสดง loading indicator หลากหลายรูปแบบ

คอมโพเนนต์พื้นฐาน

<ActivityIndicator animating={animating} color='#bc2b78' size="large" style={yourstyle} />

การนำเข้า

import { ActivityIndicator } from 'react-native';

คุณสมบัติสำคัญ

ลำดับ Props & คำอธิบาย
1 animating
ควบคุมการทำแอนิเมชัน รับค่า boolean: true = แสดง, false = ซ่อน
2 color
สีของ loading indicator
3 hidesWhenStopped
ซ่อน indicator เมื่อหยุดแอนิเมชัน ค่า true/false
4 size
ขนาดของ indicator: 'small' หรือ 'large'

ตัวอย่าง: การแสดง Loading Indicator

import { ActivityIndicator, View, StyleSheet } from 'react-native';
<ActivityIndicator
  animating={animating}
  color='#bc2b78'
  size="large"
  style={styles.activityIndicator}
/>

ตัวแปร animating ตั้งค่าเริ่มต้นเป็น true เมธอด closeActivityIndicator ถูกเรียกใน componentDidMount() จะตั้งค่า animating เป็น false หลังจาก 1 นาที (60000 ms)

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.animating;
    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;

ผลลัพธ์

วิธีแสดง Loading Indicator ใน React Native

แนวทางปฏิบัติที่ดี

  • ใช้กับการโหลดข้อมูลจาก API หรือการประมวลผลที่ใช้เวลานาน
  • ควรตั้งค่า hidesWhenStopped={true} เพื่อซ่อนอัตโนมัติเมื่อโหลดเสร็จ
  • สำหรับแอปสมัยใหม่ ควรใช้ Functional Component และ Hooks แทน Class Component