Khóa học react-native

Modal trong React Native

0 phút đọc

Modal là một component trong React Native cho phép bạn hiển thị các hộp thoại (dialog) hoặc các giao diện người dùng khác trên màn hình. Modal thường được sử dụng để hiển thị các thông báo, biểu mẫu, hoặc các tùy chọn mà người dùng cần tương tác trước khi quay lại giao diện chính. Modal cung cấp các phương thức và thuộc tính để bạn có thể tùy chỉnh và kiểm soát hành vi của nó, giúp tạo ra các trải nghiệm người dùng mượt mà và hiệu quả.

Cú Pháp Cơ Bản

Để sử dụng Modal trong React Native, bạn cần import nó từ thư viện react-native và sử dụng các thuộc tính của nó để điều chỉnh hành vi và giao diện của modal.

import React, { useState } from "react";
import { View, Text, Modal, Button, StyleSheet } from "react-native";

const App = () => {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container}>
      <Button title="Show Modal" onPress={() => setModalVisible(true)} />
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello, I am a modal!</Text>
            <Button
              title="Hide Modal"
              onPress={() => setModalVisible(!modalVisible)}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
});

export default App;

Các Thuộc Tính Quan Trọng của Modal

visible

Thuộc tính visible xác định liệu modal có hiển thị hay không. Đây là một thuộc tính bắt buộc và có giá trị boolean.

Ví dụ:

<Modal visible={modalVisible}>{/* Nội dung */}</Modal>

animationType

Thuộc tính animationType xác định kiểu hoạt hình khi modal xuất hiện và biến mất. Các giá trị có thể bao gồm none, slide, và fade.

Ví dụ:

<Modal animationType="slide">{/* Nội dung */}</Modal>

transparent

Thuộc tính transparent xác định liệu nền của modal có trong suốt hay không. Mặc định là false.

Ví dụ:

<Modal transparent={true}>{/* Nội dung */}</Modal>

onRequestClose

Thuộc tính onRequestClose là một hàm callback được gọi khi người dùng yêu cầu đóng modal. Điều này rất quan trọng trên các thiết bị Android, nơi người dùng có thể nhấn nút quay lại để đóng modal.

Ví dụ:

<Modal onRequestClose={() => setModalVisible(false)}>{/* Nội dung */}</Modal>

onShow

Thuộc tính onShow là một hàm callback được gọi khi modal được hiển thị.

Ví dụ:

<Modal onShow={() => console.log("Modal is shown")}>{/* Nội dung */}</Modal>

Ví Dụ Chi Tiết về Modal

Ví Dụ 1: Hiển Thị Modal Cơ Bản

import React, { useState } from "react";
import { View, Text, Modal, Button, StyleSheet } from "react-native";

const BasicModal = () => {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container}>
      <Button title="Show Modal" onPress={() => setModalVisible(true)} />
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Hello, I am a modal!</Text>
            <Button
              title="Hide Modal"
              onPress={() => setModalVisible(!modalVisible)}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
});

export default BasicModal;

Ví Dụ 2: Hiển Thị Modal với Nhiều Nội Dung

import React, { useState } from "react";
import { View, Text, Modal, Button, StyleSheet, TextInput } from "react-native";

const MultiContentModal = () => {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container}>
      <Button title="Show Modal" onPress={() => setModalVisible(true)} />
      <Modal
        animationType="fade"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>Enter your details</Text>
            <TextInput placeholder="Name" style={styles.input} />
            <TextInput placeholder="Email" style={styles.input} />
            <Button
              title="Submit"
              onPress={() => setModalVisible(!modalVisible)}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
  input: {
    height: 40,
    borderColor: "gray",
    borderWidth: 1,
    marginBottom: 10,
    paddingHorizontal: 10,
    width: "100%",
  },
});

export default MultiContentModal;

Ví Dụ 3: Hiển Thị Modal với Hoạt Hình Tùy Chỉnh

import React, { useState } from "react";
import { View, Text, Modal, Button, StyleSheet, Animated } from "react-native";

const CustomAnimationModal = () => {
  const [modalVisible, setModalVisible] = useState(false);
  const [fadeAnim] = useState(new Animated.Value(0));

  const showModal = () => {
    setModalVisible(true);
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 500,
      useNativeDriver: true,
    }).start();
  };

  const hideModal = () => {
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 500,
      useNativeDriver: true,
    }).start(() => {
      setModalVisible(false);
    });
  };

  return (
    <View style={styles.container}>
      <Button title="Show Modal" onPress={showModal} />
      <Modal
        transparent={true}
        visible={modalVisible}
        onRequestClose={hideModal}
      >
        <View style={styles.centeredView}>
          <Animated.View style={[styles.modalView, { opacity: fadeAnim }]}>
            <Text style={styles.modalText}>
              Hello, I am a modal with custom animation!
            </Text>
            <Button title="Hide Modal" onPress={hideModal} />
          </Animated.View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
});

export default CustomAnimationModal;

Tùy Chỉnh Modal

Sử Dụng Các Tùy Chọn Tùy Chỉnh

Bạn có thể sử dụng các tùy chọn tùy chỉnh để thay đổi giao diện và hành vi của modal.

Ví dụ:

import React, { useState } from "react";
import { View, Text, Modal, Button, StyleSheet } from "react-native";

const CustomModal = () => {
  const [modalVisible, setModalVisible] = useState(false);

  return (
    <View style={styles.container}>
      <Button title="Show Modal" onPress={() => setModalVisible(true)} />
      <Modal
        animationType="slide"
        transparent={true}
        visible={modalVisible}
        onRequestClose={() => {
          setModalVisible(!modalVisible);
        }}
      >
        <View style={styles.centeredView}>
          <View style={styles.modalView}>
            <Text style={styles.modalText}>This is a custom modal</Text>
            <Button
              title="Hide Modal"
              onPress={() => setModalVisible(!modalVisible)}
            />
          </View>
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  centeredView: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "rgba(0,0,0,0.5)",
  },
  modalView: {
    margin: 20,
    backgroundColor: "white",
    borderRadius: 20,
    padding: 35,
    alignItems: "center",
    shadowColor: "#000",
    shadowOffset: {
      width: 0,
      height: 2,
    },
    shadowOpacity: 0.25,
    shadowRadius: 4,
    elevation: 5,
  },
  modalText: {
    marginBottom: 15,
    textAlign: "center",
  },
});

export default CustomModal;

Sử Dụng Thư Viện Bên Ngoài

Nếu bạn cần các tính năng phức tạp hơn, bạn có thể sử dụng các thư viện bên ngoài như react-native-modal hoặc react-native-dialog.

Sử Dụng react-native-modal

Cài Đặt Thư Viện

npm install react-native-modal

Sử Dụng Thư Viện

import React, { useState } from "react";
import { View, Text, Button, StyleSheet } from "react-native";
import Modal from "react-native-modal";

const CustomModal = () => {
  const [isModalVisible, setModalVisible] = useState(false);

  const toggleModal = () => {
    setModalVisible(!isModalVisible);
  };

  return (
    <View style={styles.container}>
      <Button title="Show Modal" onPress={toggleModal} />
      <Modal isVisible={isModalVisible}>
        <View style={styles.modalContent}>
          <Text>Hello!</Text>
          <Button title="Hide Modal" onPress={toggleModal} />
        </View>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  modalContent: {
    backgroundColor: "white",
    padding: 22,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 4,
    borderColor: "rgba(0, 0, 0, 0.1)",
  },
});

export default CustomModal;

Sử Dụng react-native-dialog

Cài Đặt Thư Viện

npm install react-native-dialog

Sử Dụng Thư Viện

import React, { useState } from "react";
import { View, Button, StyleSheet } from "react-native";
import Dialog from "react-native-dialog";

const CustomDialog = () => {
  const [visible, setVisible] = useState(false);

  const showDialog = () => {
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
  };

  const handleOK = () => {
    setVisible(false);
    console.log("OK Pressed");
  };

  return (
    <View style={styles.container}>
      <Button title="Show Dialog" onPress={showDialog} />
      <Dialog.Container visible={visible}>
        <Dialog.Title>Dialog Title</Dialog.Title>
        <Dialog.Description>
          This is a custom dialog message.
        </Dialog.Description>
        <Dialog.Button label="Cancel" onPress={handleCancel} />
        <Dialog.Button label="OK" onPress={handleOK} />
      </Dialog.Container>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
});

export default CustomDialog;
Avatar
Được viết bởi

TechMely Team

Gợi ý câu hỏi phỏng vấn

Gợi ý bài viết

Bình luận

Chưa có bình luận nào

Khoá học javascript từ cơ bản đến chuyên sâuYoutube Techmely