您好,欢迎访问一九零五行业门户网

如何在 ReactNative 中使用警报对话框?

警报组件有助于显示一个对话框,即向用户弹出一个带有标题、消息、按钮的弹出窗口,以便根据显示的消息了解用户的确认。
基本组件警报如下 -
alert.alert('yourtile', 'yourmessage', [yourbuttons], ‘options’)
要使用警报组件,您需要按如下方式导入它 -
import { alert } from 'react-native';
要获取弹出窗口,您只需调用 alert.alert() 函数。 alert() 有四个参数,分别是标题、消息、按钮和选项。标题是强制参数,其余参数是可选的。
这是一个关于如何使用 alert.alert() 的简单示例 -
alert.alert( "hi", "do you want to continue?", [ { text: "later", onpress: () => console.log("user pressed later") }, { text: "cancel", onpress: () => console.log("cancel pressed"), style: "cancel" }, { text: "ok", onpress: () => console.log("ok pressed") } ], { cancelable: false });
这里的标题是“嗨”,消息是“你想继续吗”,我想在对话框中显示的按钮是“稍后”、“取消”和“确定”。对于添加的每个按钮 onpress 事件,该事件显示一条控制台消息。最后是选项参数,它可以用来控制弹出窗口的行为。在 android 上,默认情况下,如果在弹出窗口边界外单击,弹出窗口将关闭。要禁用它,您可以使用 { cancelable: false } 作为选项参数。当您点击弹出区域之外时,由于可取消设置为 false,它不会关闭。
在 ios 中,您可以指定任意数量的按钮,但在 android 中,您可以使用三个按钮。 android 中的三个按钮具有中性、消极和积极按钮的概念 -
如果指定一个按钮,它将类似于“积极” ' 例如“确定”。
如果有两个按钮,第一个为“负”,第二个为“正”。例如“取消”和“确定”。如果是三个按钮,则为“中性”、“消极”、“积极”。例如“稍后”、“取消”和“确定”
这是一个显示警报组件工作原理的工作示例 -
示例 1:警报框的显示import react from 'react';import { button, view, alert } from 'react-native';const app = () => { const testalert = () => alert.alert( "hi", "do you want to continue?", [ { text: "later", onpress: () => console.log("user pressed later") }, { text: "cancel", onpress: () => console.log("cancel pressed"), style: "cancel" }, { text: "ok", onpress: () => console.log("ok pressed") } ], { cancelable: false } ); return ( <view style={{flex :1, justifycontent: 'center', margin: 15 }}> <button title="click me" color="#9c27b0" onpress={testalert} /> </view> );}export default app;
输出
示例 2:在 android 中使用 {cancelable: true }在下面的示例中,{cancelable: true } 与标题、消息和按钮一起使用。所以警报框将如下所示 -
alert.alert( "hi", "do you want to continue?", [ { text: "later", onpress: () => console.log("user pressed later") }, { text: "cancel", onpress: () => console.log("cancel pressed"), style: "cancel" }, { text: "ok", onpress: () => console.log("ok pressed") } ], { cancelable: true });
完整的工作示例如下 -
import react from 'react';import { button, view, alert } from 'react-native';const app = () => { const testalert = () => alert.alert( "hi", "do you want to continue?", [ { text: "later", onpress: () => console.log("user pressed later") }, { text: "cancel", onpress: () => console.log("cancel pressed"), style: "cancel" }, { text: "ok", onpress: () => console.log("ok pressed") } ], { cancelable: true } ); return ( <view style={{flex :1, justifycontent: 'center', margin: 15 }}> <button title="click me" color="#9c27b0" onpress={testalert} /> </view> );}export default app;
当您点击弹出区域之外时,它将关闭。
输出
以上就是如何在 reactnative 中使用警报对话框?的详细内容。
其它类似信息

推荐信息