如何在 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
}
})输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP