React Native - 弹出框、对话框组件(AlertIOS)的使用详解
作者:hangge | 2017-03-16 08:10
在开发 App 的时候,经常会使用到对话框(又叫消息框、提示框、告警框)。在 Web 开发中通常使用 alert 来实现,虽然方便但比较简陋。而 React Native 为我们提供了原生的对话框,那就是:AlertIOS 和 Alert。
一、AlertIOS组件介绍
看名字就知道 AlertIOS 组件只适用于 iOS 设备,其提供的功能比 Alert 组件会更多些。
1,对话框类型
AlertIOS 提供两个静态方法,分别对应两种类型的对话框:
- alert(title, message, buttons):普通的消息提示对话框。其中 buttons 是对象数组。
- prompt(title, value, buttons):提供可输入的对话框。其中 buttons 是对象数组。
2,对话框样式
- 如果没有设置 buttons 数组,AlertIOS 组件默认会有一个“确认”按钮。
- 默认情况下,buttons 数组的最后一个按钮会高亮显示。
- 如果数组的长度过长按钮就会垂直排列。
3,使用样例
(1)效果图
- 点击界面上的“提示对话框”按钮,会弹出一个消息提示框。
- 点击界面上的“输入对话框”按钮,会弹出一个带输入框的提示框。

(2)样例代码
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
AlertIOS
} from 'react-native';
//默认应用的容器组件
class App extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.item} onPress={this.tip.bind(this)}>提示对话框</Text>
<Text style={styles.item} onPress={this.input.bind(this)}>输入对话框</Text>
</View>
);
}
//弹出提示对话框
tip() {
AlertIOS.alert('提示', '欢迎访问hangge.com', [
{
text: '取消',
onPress: function() {
console.log('取消按钮点击');
}
},
{
text: '确认',
onPress: function() {
console.log('确认按钮点击');
}
},
])
}
//弹出输入对话框
input() {
AlertIOS.prompt('提示', '请出输入内容...', [
{
text: '取消',
onPress: function() {
console.log('取消按钮点击');
}
},
{
text: '确认',
onPress: function() {
console.log('确认按钮点击');
}
},
])
}
}
//样式定义
const styles = StyleSheet.create({
container:{
flex: 1,
marginTop:25
},
item:{
marginTop:10,
marginLeft:5,
marginRight:5,
height:30,
borderWidth:1,
padding:6,
borderColor:'#ddd',
textAlign:'center'
},
});
AppRegistry.registerComponent('HelloWorld', () => App);
二、Alert组件介绍
Alert 组件是 iOS 设备和 Android 设备都通用的。不过它只有一个普通的消息提示对话框类型。- alert(title, message, buttons):普通的消息提示对话框。其中 buttons 是对象数组。
全部评论(0)