跳到主要内容
新架构实战课 实操 + 基建 + 原理全维度包揽,抢先掌握 React Native 新架构精髓 立即查看 >

Alert

启动一个提示对话框,包含对应的标题和信息。

你还可以指定一系列的按钮,点击对应的按钮会调用对应的 onPress 回调并且关闭提示框。默认情况下,对话框会仅有一个'确定'按钮。

本接口可以在 iOS 和 Android 上显示一个静态的提示框。只有 iOS 系统支持在提示框中加入文本框。

示例

iOS

在 iOS 上你可以指定任意数量的按钮。每个按钮还都可以指定自己的样式,此外还可以指定提示的类别。参阅AlertButtonStyle来了解更多细节。

Android

在 Android 上最多能指定三个按钮,这三个按钮分别具有“中间态”、“消极态”和“积极态”的概念:

如果你只指定一个按钮,则它具有“积极态”的属性(比如“确定”);两个按钮,则分别是“消极态”和“积极态”(比如“取消”和“确定”);三个按钮则意味着“中间态”、“消极态”和“积极态”(比如“稍候再说”,“取消”,“确定”)。

在 Android 上可以通过点击提示框的外面来取消提示框,但这一行为默认没有启用。你可以在Options中提供一个额外参数来启用这一行为:{ cancelable: true }

还可以通过在options中添加onDismiss回调函数来捕获用户的取消操作:{ onDismiss: () => {} }

示例
Android


文档

方法

alert()

static alert(title, message?, buttons?, options?)

参数:

名称类型说明
titlestring
Required
The dialog's title. Passing null or empty string will hide the title.
messagestringAn optional message that appears below the dialog's title.
buttonsButtonsAn optional array containg buttons configuration.
optionsOptions
Android
An optional Alert configuration for the Android.

prompt()
iOS

static prompt(title, message?, callbackOrButtons?, type?, defaultValue?, keyboardType?)

Create and display a prompt to enter some text in form of Alert.

参数:

名称类型说明
titlestring
Required
The dialog's title.
messagestringAn optional message that appears above the text input.
callbackOrButtonsfunction
Buttons
If passed a function, it will be called with the prompt's value
(text: string) => void, when the user taps 'OK'.
If passed an array, buttons will be configured based on the array content.
类型AlertTypeThis configures the text input.
defaultValuestringThe default text in text input.
keyboardTypestringThe keyboard type of first text field (if exists). One of TextInput keyboardTypes.

类型定义

AlertButtonStyle
iOS

An iOS Alert button style.

类型
enum

常量:

Value说明
'default'Default button style.
'cancel'Cancel button style.
'destructive'Destructive button style.

AlertType
iOS

An iOS Alert type.

类型
enum

常量:

说明
'default'Default alert with no inputs
'plain-text'Plain text input alert
'secure-text'Secure text input alert
'login-password'Login and password alert

Buttons

Array of objects containg Alert buttons configuration.

类型
array of objects

Objects properties:

名称类型说明
textstringButton label.
onPressfunctionCallback function when button is pressed.
style
iOS
AlertButtonStyleButton style, on Android this property will be ignored.

Options
Android

类型
object

属性:

名称类型说明
cancelablebooleanDefines if alert can be dismissed by tapping outside of the alert box.
onDismissfunctionCallback function fired when alert has been dismissed.