如何在 React Native 中使用 Alert 對話方塊?
Alert 元件用於向用戶顯示一個對話方塊,即彈出視窗,其中包含標題、訊息和按鈕,以便根據顯示的訊息獲取使用者的確認。
Alert 的基本元件如下所示:
Alert.alert('yourtile', 'yourmessage', [yourbuttons], ‘options’)
要使用 Alert 元件,您需要按如下方式匯入它:
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 } );
這裡的標題是“Hi”,訊息是“Do you want to continue”,我想在對話方塊中顯示的按鈕是“稍後”、“取消”和“確定”。每個按鈕都添加了 onPress 事件,該事件顯示一條控制檯訊息。最後一個是選項引數,可用於控制彈出視窗的行為。在 Android 中,預設情況下,如果點選彈出視窗邊界之外,彈出視窗將關閉。要停用此功能,您可以使用 { cancelable: false } 作為選項引數。當您點選彈出視窗區域之外時,由於 cancelable 設定為 false,因此它不會關閉。
在 iOS 中,您可以指定任意數量的按鈕,但在 Android 中,您可以使用三個按鈕。Android 中的三個按鈕具有中性、負面和正面按鈕的概念,例如:
如果指定一個按鈕,它將類似於“正面”按鈕,例如“確定”。
如果兩個按鈕,第一個將是“負面”按鈕,第二個將是“正面”按鈕。例如“取消”和“確定”。
如果三個按鈕,則將是“中性”、“負面”、“正面”。例如“稍後”、“取消”和“確定”。
以下是一個工作示例,展示了 Alert 元件的工作原理:
示例 1:顯示 Alert 對話方塊
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.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;
當您點選彈出視窗區域之外時,它將關閉。