React Native - 弹出确认框、弹出选择框(Alert)的使用详解
作者:hangge | 2017-08-29 08:10
弹出确认框与弹出询问框是移动应用程序开发中经常需要使用的 UI 手段。React Native 已经为我们提供了原生的对话框组件:AlertIOS 和 Alert。
而本文介绍的 Alert API 虽然只有一个普通的消息提示对话框类型,但它是 iOS 设备和 Android 设备都通用的。
1,弹出确认框
如果弹出框只给用户一个选择,或者不给选择。那它就是弹出确认框。
(1)下面是一个简单的样例
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Alert,
View,
Text,
} from 'react-native';
class Main extends Component {
render() {
return (
<View style={styles.flex}>
<Text style={styles.back_text} onPress={this.showAlert.bind(this)}>
弹出
</Text>
</View>
);
}
showAlert() {
Alert.alert('标题内容','正文内容');
}
}
const styles = StyleSheet.create({
flex:{
flex:1
},
back_text:{
width: 80,
backgroundColor: 'gray',
color: 'white',
textAlign: 'center',
fontSize: 18,
alignSelf: 'center',
marginTop: 20
}
});
AppRegistry.registerComponent('HelloWorld', () => Main);
当我们点击“弹出”按钮会弹出一个确认框:

(2)默认情况下确认框的按钮自动叫“OK”,我们也可以提供按钮名称。比如我们将确认按钮修改成“我知道了”

Alert.alert('标题内容','正文内容',[{text:"我知道了"}]);
(3)除了提供按钮名称,还可以指定回调函数。下面代码,当用户点击了“我知道了”按钮后,confirm 函数会被执行。
Alert.alert('标题内容','正文内容',
[{text:"我知道了", onPress:this.confirm}]
);
2,弹出选择框
如果弹出框给了多个选择。那它就是弹出选择框。选项个数上限在 Android 和 iOS 下稍有不同:
- Android 平台:弹出选择框最多只能有三个选项
- iOS 平台:弹出选择框没有选项个数的显示。
(1)下面是一个简单的样例
Alert.alert('标题内容','正文内容',
[
{text:"选项一", onPress:this.opntion1Selected},
{text:"选项二", onPress:this.opntion2Selected},
{text:"选项三", onPress:this.opntion3Selected},
{text:"选项四", onPress:this.opntion4Selected},
]
);
(2)可以看到在 Android 设备下,第四个选项显示不出来。而 iOS 设备是没有这个问题的。

3,手机返回键按下的效果
当弹出框显示时,按下手机的返回键会让弹出框消失,并且不会触发任何给 Alert API 提供的回调函数。
全部评论(0)