คอมโพเนนต์ Modal ช่วยแสดงมุมมองเนื้อหา (content view) เหนือ UI หลักของแอป
คอมโพเนนต์พื้นฐาน
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => { Alert.alert("Modal has been closed."); }}
>
Your Content Here
</Modal>
การนำเข้า
import { Modal } from "react-native";
คุณสมบัติสำคัญของ Modal
| ลำดับ | Props & คำอธิบาย |
|---|---|
| 1 | animationType จัดการแอนิเมชันการแสดง modal: 'slide', 'fade', 'none' |
| 2 | onDismiss ฟังก์ชันที่เรียกเมื่อ modal ถูกปิด |
| 3 | onOrientationChange Callback เมื่อทิศทางอุปกรณ์เปลี่ยนขณะ modal แสดง |
| 4 | onShow ฟังก์ชันที่เรียกเมื่อ modal แสดง |
| 5 | presentationStyle รูปแบบการแสดง: 'fullScreen', 'pageSheet', 'formSheet', 'overFullScreen' (iOS) |
| 6 | transparent ตัดสินใจให้มุมมองโปร่งใสหรือเต็มจอ |
| 7 | visible ควบคุมการแสดง/ซ่อน modal |
ตัวอย่างที่ 1: แสดง Modal Window
import { Modal } from "react-native";
ตัวอย่างแสดง modal แบบง่ายพร้อมข้อความและปุ่ม:
<Modal
animationType="slide"
transparent={true}
visible={isVisible}
>
<View style={styles.centeredView}>
<View style={styles.myModal}>
<Text style={styles.modalText}>Modal Window Testing!</Text>
<Button style={styles.modalButton} title="Close" onPress={() => { setModalVisiblility(false); }} />
</View>
</View>
</Modal>
ตัวแปร isVisible ผูกกับ prop visible ค่าเริ่มต้น false (ไม่แสดง)
const [isVisible, setModalVisiblility] = useState(false);
ปุ่ม Close เรียก setModalVisiblility(false) ทำให้ modal หายไป
ปุ่มนอก modal เรียก setModalVisiblility(true) เพื่อแสดง modal
import React, { useState } from "react";
import { Button, Alert, Modal, StyleSheet, Text, View } from "react-native";
const App = () => {
const [isVisible, setModalVisiblility] = useState(false);
return (
Modal Window Testing!
);
};
const styles = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
myModal: {
width: 200,
height: 200,
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.30,
shadowRadius: 4,
elevation: 5
},
modalText: {
marginBottom: 20,
textAlign: "center"
},
modalButton: {
marginBottom: 50
}
});
export default App;
ผลลัพธ์

หมายเหตุ
- Modal เป็นคอมโพเนนต์พื้นฐานของ React Native ไม่ต้องติดตั้งเพิ่ม
- สำหรับ modal ที่ซับซ้อนมากขึ้น ควรพิจารณาใช้ไลบรารีเช่น
react-native-modalหรือreact-navigation(modal stack) - บน Android ต้องจัดการ hardware back button ให้ปิด modal ได้