Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การใช้งาน Alert Dialog Box ใน React Native


คอมโพเนนต์ Alert ช่วยแสดงกล่องโต้ตอบ (dialog box) หรือป๊อปอัปให้ผู้ใช้ พร้อม tiêu đề ข้อความ และปุ่ม เพื่อยืนยันจากผู้ใช้ตามข้อความที่แสดง

คอมโพเนนต์พื้นฐาน

Alert.alert('yourTitle', 'yourMessage', [yourButtons], 'options')

การนำเข้า

import { Alert } from 'react-native';

เพื่อแสดงป๊อปอัป ให้เรียก Alert.alert() ฟังก์ชันรับ 4 พารามิเตอร์: title (บังคับ), message, buttons, และ options (ตัวเลือก)

ตัวอย่างง่าย

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 }
);

พารามิเตอร์ options ใช้ควบคุมพฤติกรรมของป๊อปอัป บน Android โดยค่าเริ่มต้น ป๊อปอัปจะปิดหากคลิกนอกพื้นที่ ตั้งค่า { cancelable: false } เพื่อปิดการทำงานนี้

ความแตกต่างระหว่าง iOS และ Android

  • iOS: รองรับปุ่มไม่จำกัดจำนวน
  • Android: จำกัด 3 ปุ่ม โดยมีแนวคิด neutral, negative, positive:
    • 1 ปุ่ม: positive (เช่น "OK")
    • 2 ปุ่ม: negative, positive (เช่น "Cancel", "OK")
    • 3 ปุ่ม: neutral, negative, positive (เช่น "Later", "Cancel", "OK")

ตัวอย่างที่ 1: แสดง Alert Box

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 (
    
      

ผลลัพธ์

การใช้งาน Alert Dialog Box ใน React Native

ตัวอย่างที่ 2: ใช้ { cancelable: true } สำหรับ Android

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 }
);

เมื่อคลิกนอกพื้นที่ป๊อปอัป จะถูกปิดอัตโนมัติ

ผลลัพธ์

การใช้งาน Alert Dialog Box ใน React Native