如何在 React Native 中顯示載入指示器?
當我們想要告訴使用者他們在 UI 上發出的請求需要一些時間時,就會使用載入指示器。例如,使用者在填寫表單後點擊提交按鈕,或者點選搜尋按鈕獲取一些資料。
ReactNative 提供了一個 ActivityIndicator 元件,它有不同的方式在 UI 上顯示載入指示器。
基本的 ActivityIndicator 元件如下所示:
<ActivityIndicator animating = {animating} color = '#bc2b78' size = "large" style = {yourstyle}/>
要使用 ActivityIndicator,你需要像下面這樣匯入它:
import { ActivityIndicator} from 'react-native';
以下是 ActivityIndicator 可用的部分重要屬性。
序號 | 屬性 & 描述 |
---|---|
1 | animating 用於動畫化載入指示器。它接受布林值 true 來顯示指示器,false 來隱藏它。 |
2 | color 載入指示器要顯示的顏色。 |
3 | hidesWhenStopped 在不動畫時停止指示器。值為 true/false。 |
4 | size 指示器的大小。值為 small 和 large。 |
示例:顯示載入指示器
載入指示器是使用 ActivityIndicator 實現的,所以首先匯入它:
import { ActivityIndicator, View, StyleSheet } from 'react-native';
這是使用的 ActivityIndicator 元件:
<ActivityIndicator animating = {animating} color = '#bc2b78' size = "large" style = {styles.activityIndicator}/>
animating 設定為 animating 變數,預設情況下設定為 true。closeActivityIndicator 方法在 componentDidMount() 函式中呼叫,它將在 1 分鐘後將 animating 狀態設定為 false。
state = { animating: true } closeActivityIndicator = () => setTimeout(() => this.setState({ animating: false }), 60000) componentDidMount = () => this.closeActivityIndicator()
這是一個顯示載入指示器的完整程式碼:
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 ( <View style = {styles.container}> <ActivityIndicator animating = {animating} color = '#bc2b78' size = "large" style = {styles.activityIndicator}/> </View> ) } } export default ActivityIndicatorExample const styles = StyleSheet.create ({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', marginTop: 70 }, activityIndicator: { flex: 1, justifyContent: 'center', alignItems: 'center', height: 80 } })
輸出
廣告