Khóa học react-native

Alert trong React Native

0 phút đọc

Alert là một module trong React Native cho phép bạn hiển thị các hộp thoại cảnh báo (alert dialogs) native trên cả hai nền tảng iOS và Android. Hộp thoại cảnh báo là một cách tuyệt vời để cung cấp thông tin quan trọng cho người dùng hoặc yêu cầu họ thực hiện một hành động nào đó. Alert cung cấp các phương thức để hiển thị các hộp thoại cảnh báo với nhiều tùy chọn khác nhau, bao gồm các nút hành động và các thông điệp tùy chỉnh.

Cú Pháp Cơ Bản

Để sử dụng Alert trong React Native, bạn cần import nó từ thư viện react-native và sử dụng các phương thức của nó để hiển thị hộp thoại cảnh báo.

import React from "react";
import { View, Button, Alert, StyleSheet } from "react-native";

const App = () => {
  const showAlert = () => {
    Alert.alert("Alert Title", "My Alert Msg", [
      { text: "OK", onPress: () => console.log("OK Pressed") },
    ]);
  };

  return (
    <View style={styles.container}>
      <Button title="Show Alert" onPress={showAlert} />
    </View>
  );
};

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

export default App;

Các Phương Thức Quan Trọng của Alert

alert

Phương thức alert được sử dụng để hiển thị một hộp thoại cảnh báo. Nó nhận vào ba tham số chính: tiêu đề, thông điệp, và một mảng các nút hành động.

Cú pháp:

Alert.alert(title, message, buttons, options);

Ví dụ:

Alert.alert("Alert Title", "My Alert Msg", [
  { text: "OK", onPress: () => console.log("OK Pressed") },
]);

Các Tùy Chọn của Alert

Dưới đây là một số tùy chọn mà bạn có thể sử dụng với Alert.alert:

  • title: Tiêu đề của hộp thoại cảnh báo.
  • message: Thông điệp hiển thị trong hộp thoại cảnh báo.
  • buttons: Một mảng các đối tượng đại diện cho các nút hành động.
  • options: Một đối tượng chứa các tùy chọn bổ sung như cancelableonDismiss.

Các Tùy Chọn của Nút Hành Động

Dưới đây là một số tùy chọn mà bạn có thể sử dụng với các nút hành động:

  • text: Văn bản hiển thị trên nút.
  • onPress: Hàm callback được gọi khi nút được nhấn.
  • style: Kiểu của nút, có thể là default, cancel, hoặc destructive.

Ví Dụ Chi Tiết về Alert

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

import React from "react";
import { View, Button, Alert, StyleSheet } from "react-native";

const BasicAlert = () => {
  const showAlert = () => {
    Alert.alert("Alert Title", "My Alert Msg", [
      { text: "OK", onPress: () => console.log("OK Pressed") },
    ]);
  };

  return (
    <View style={styles.container}>
      <Button title="Show Alert" onPress={showAlert} />
    </View>
  );
};

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

export default BasicAlert;

Ví Dụ 2: Hiển Thị Alert với Nhiều Nút Hành Động

import React from "react";
import { View, Button, Alert, StyleSheet } from "react-native";

const MultiButtonAlert = () => {
  const showAlert = () => {
    Alert.alert("Alert Title", "My Alert Msg", [
      {
        text: "Ask me later",
        onPress: () => console.log("Ask me later pressed"),
      },
      {
        text: "Cancel",
        onPress: () => console.log("Cancel Pressed"),
        style: "cancel",
      },
      { text: "OK", onPress: () => console.log("OK Pressed") },
    ]);
  };

  return (
    <View style={styles.container}>
      <Button title="Show Alert" onPress={showAlert} />
    </View>
  );
};

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

export default MultiButtonAlert;

Ví Dụ 3: Hiển Thị Alert với Tùy Chọn Hủy

import React from "react";
import { View, Button, Alert, StyleSheet } from "react-native";

const CancelableAlert = () => {
  const showAlert = () => {
    Alert.alert(
      "Alert Title",
      "My Alert Msg",
      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel",
        },
        { text: "OK", onPress: () => console.log("OK Pressed") },
      ],
      { cancelable: true, onDismiss: () => console.log("Alert dismissed") }
    );
  };

  return (
    <View style={styles.container}>
      <Button title="Show Alert" onPress={showAlert} />
    </View>
  );
};

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

export default CancelableAlert;

Tùy Chỉnh Alert

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 hộp thoại cảnh báo.

Ví dụ:

import React from "react";
import { View, Button, Alert, StyleSheet } from "react-native";

const CustomAlert = () => {
  const showAlert = () => {
    Alert.alert(
      "Custom Alert Title",
      "This is a custom alert message",
      [
        {
          text: "Cancel",
          onPress: () => console.log("Cancel Pressed"),
          style: "cancel",
        },
        { text: "OK", onPress: () => console.log("OK Pressed") },
      ],
      { cancelable: false }
    );
  };

  return (
    <View style={styles.container}>
      <Button title="Show Custom Alert" onPress={showAlert} />
    </View>
  );
};

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

export default CustomAlert;

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

Nếu bạn cần các hộp thoại cảnh báo 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-dialog hoặc react-native-modal.

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;

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, Button, Text, 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;

Các Kỹ Thuật Tối Ưu Hóa Sử Dụng Alert

Sử Dụng StyleSheet để Tối Ưu Hóa Hiệu Suất

Sử dụng StyleSheet.create để định nghĩa các style giúp tối ưu hóa hiệu suất vì các style được tạo ra chỉ một lần và được tham chiếu lại nhiều lần.

Ví dụ:

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

Tránh Sử Dụng Hàm Inline

Tránh sử dụng các hàm inline cho thuộc tính onPress để tránh việc tạo lại hàm mỗi khi component được render.

Ví dụ:

const showAlert = () => {
  Alert.alert("Alert Title", "My Alert Msg", [
    { text: "OK", onPress: () => console.log("OK Pressed") },
  ]);
};

<Button title="Show Alert" onPress={showAlert} />;

Các Hạn Chế của Alert Component

Mặc dù Alert component trong React Native rất mạnh mẽ, nhưng nó cũng có một số hạn chế:

  1. Tùy Chỉnh Giao Diện: Alert không hỗ trợ nhiều tùy chỉnh giao diện như thay đổi font chữ, thêm biểu tượng, hoặc tạo nền gradient.
  2. Quản Lý Sự Kiện: Khi có nhiều sự kiện lắng nghe được đăng ký, việc quản lý và loại bỏ chúng có thể trở nên phức tạp.
  3. Hiệu Suất: Khi sử dụng quá nhiều Alert lồng nhau, hiệu suất của ứng dụng có thể bị ảnh hưởng.

Kết Luận

Alert là một thành phần cơ bản và quan trọng trong React Native, giúp bạn tạo ra các giao diện người dùng mượt mà và hiệu quả. Bằng cách hiểu rõ các thuộc tính và cách sử dụng Alert, bạn có thể tạo ra các giao diện người dùng mượt mà và hiệu quả. Hy vọng qua bài viết này, bạn đã có thể nắm bắt được cách sử dụng Alert trong React Native và áp dụng vào các dự án của mình.

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