在开发 App 的时候,经常会使用到对话框(又叫消息框、提示框、告警框)。在 Web 开发中通常使用 alert 来实现,虽然方便但比较简陋。而 React Native 为我们提供了原生的对话框,那就是:AlertIOS 和 Alert。
AlertIOS 用于弹出一个 iOS 提示对话框,可以通知用户一些信息或是提示用户输入一些文字。
方法
1. alert()
创建并显示一个普通的消息提示对话框。
名称 | 类型 | 必填 | 说明 |
---|---|---|---|
title | string | 是 | 对话框的标题。 |
message | string | 否 | 显示在对话框标题下方的可选消息。 |
callbackOrButtons | 箭头函数 | 否 | 此可选参数应该是单参数函数或按钮数组。 |
type | AlertType | 否 | 不推荐使用 |
2. prompt()
创建并显示输入某些文本的提示框。
名称 | 类型 | 必填 | 说明 |
---|---|---|---|
title | string | 是 | 对话框的标题。 |
message | string | 否 | 显示在对话框标题下方的可选消息。 |
callbackOrButtons | 箭头函数 | 否 | 此可选参数应该是单参数函数或按钮数组。 |
type | AlertType | 否 | 不推荐使用 |
defaultValue | string | 否 | 文本输入中的默认文本。 |
keyboardType | string | 否 | 第一个文本字段的键盘类型 |
实例
1. 逻辑代码
import React, {Component} from 'react';
import {
StyleSheet,
Text,
AlertIOS,
View
} from 'react-native';
export default class App extends Component {
render() {
return (
<View style = {styles.container}>
<Text
style={styles.text}
onPress = {
this.tip.bind(this)
}
>提示对话框</Text>
<Text
style={styles.text}
onPress = {
this.input.bind(this)
}
>输入对话框</Text>
</View>
);
}
tip() {
AlertIOS.alert('提示','欢迎访问我的简书',[
{
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,
paddingTop: 30,
backgroundColor: '#F5FCFF',
},
text: {
marginTop:10,
marginLeft:5,
marginRight:5,
height:30,
borderWidth:1,
padding:6,
borderColor:'green',
textAlign:'center'
},
});
2. 效果图


小提示:
在 iOS 模拟器中按下 ⌘-R 就可以刷新 APP 并看到你的最新修改!
网友评论