Khóa học react-native

Dimensions trong React Native

0 phút đọc

Dimensions là một module trong React Native cho phép bạn truy cập vào các thông tin về kích thước của màn hình thiết bị. Điều này rất hữu ích khi bạn cần tạo ra các giao diện người dùng linh hoạt và đáp ứng, phù hợp với nhiều kích thước màn hình khác nhau. Dimensions cung cấp các phương thức để lấy chiều rộng và chiều cao của màn hình, cũng như lắng nghe các thay đổi về kích thước màn hình.

Cú Pháp Cơ Bản

Để sử dụng Dimensions 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ó để lấy thông tin về kích thước màn hình.

javascript Copy
import React from "react";
import { View, Text, Dimensions, StyleSheet } from "react-native";

const App = () => {
  const { width, height } = Dimensions.get("window");

  return (
    <View style={styles.container}>
      <Text>Width: {width}</Text>
      <Text>Height: {height}</Text>
    </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 Dimensions

get

Phương thức get được sử dụng để lấy thông tin về kích thước của màn hình. Nó nhận vào một tham số là window hoặc screen và trả về một đối tượng chứa chiều rộng và chiều cao của màn hình.

Cú pháp:

javascript Copy
Dimensions.get(dimension);

Ví dụ:

javascript Copy
const { width, height } = Dimensions.get("window");

addEventListener

Phương thức addEventListener được sử dụng để lắng nghe các thay đổi về kích thước màn hình. Nó nhận vào hai tham số: tên sự kiện (change) và một hàm callback để xử lý sự kiện.

Cú pháp:

javascript Copy
Dimensions.addEventListener(eventName, handler);

Ví dụ:

javascript Copy
Dimensions.addEventListener("change", ({ window: { width, height } }) => {
  console.log(`Width: ${width}, Height: ${height}`);
});

removeEventListener

Phương thức removeEventListener được sử dụng để loại bỏ một sự kiện lắng nghe đã được đăng ký trước đó. Điều này rất quan trọng để tránh rò rỉ bộ nhớ.

Cú pháp:

javascript Copy
Dimensions.removeEventListener(eventName, handler);

Ví dụ:

javascript Copy
Dimensions.removeEventListener("change", handler);

Ví Dụ Chi Tiết về Dimensions

Ví Dụ 1: Lấy Kích Thước Màn Hình

javascript Copy
import React from "react";
import { View, Text, Dimensions, StyleSheet } from "react-native";

const ScreenDimensions = () => {
  const { width, height } = Dimensions.get("window");

  return (
    <View style={styles.container}>
      <Text>Width: {width}</Text>
      <Text>Height: {height}</Text>
    </View>
  );
};

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

export default ScreenDimensions;

Ví Dụ 2: Lắng Nghe Thay Đổi Kích Thước Màn Hình

javascript Copy
import React, { useState, useEffect } from "react";
import { View, Text, Dimensions, StyleSheet } from "react-native";

const ResponsiveScreen = () => {
  const [dimensions, setDimensions] = useState(Dimensions.get("window"));

  useEffect(() => {
    const handler = ({ window }) => {
      setDimensions(window);
    };

    Dimensions.addEventListener("change", handler);

    return () => {
      Dimensions.removeEventListener("change", handler);
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text>Width: {dimensions.width}</Text>
      <Text>Height: {dimensions.height}</Text>
    </View>
  );
};

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

export default ResponsiveScreen;

Ví Dụ 3: Tạo Giao Diện Linh Hoạt

javascript Copy
import React from "react";
import { View, Text, Dimensions, StyleSheet } from "react-native";

const FlexibleLayout = () => {
  const { width, height } = Dimensions.get("window");
  const isPortrait = height > width;

  return (
    <View
      style={isPortrait ? styles.portraitContainer : styles.landscapeContainer}
    >
      <Text style={styles.text}>
        Orientation: {isPortrait ? "Portrait" : "Landscape"}
      </Text>
    </View>
  );
};

const styles = StyleSheet.create({
  portraitContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "lightblue",
  },
  landscapeContainer: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
    backgroundColor: "lightgreen",
  },
  text: {
    fontSize: 24,
  },
});

export default FlexibleLayout;

Tùy Chỉnh Giao Diện với Dimensions

Sử Dụng Dimensions để Tạo Giao Diện Linh Hoạt

Bạn có thể sử dụng Dimensions để tạo ra các giao diện linh hoạt, phù hợp với nhiều kích thước màn hình khác nhau.

Ví dụ:

javascript Copy
import React from "react";
import { View, Text, Dimensions, StyleSheet } from "react-native";

const ResponsiveLayout = () => {
  const { width, height } = Dimensions.get("window");
  const isSmallScreen = width < 360;

  return (
    <View style={styles.container}>
      <Text style={isSmallScreen ? styles.smallText : styles.largeText}>
        This is a {isSmallScreen ? "small" : "large"} screen
      </Text>
    </View>
  );
};

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

export default ResponsiveLayout;

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-responsive-screen hoặc react-native-size-matters.

Sử Dụng react-native-responsive-screen

Cài Đặt Thư Viện

bash Copy
npm install react-native-responsive-screen

Sử Dụng Thư Viện

javascript Copy
import React from "react";
import { View, Text, StyleSheet } from "react-native";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp,
} from "react-native-responsive-screen";

const ResponsiveScreenExample = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>Width: {wp("50%")}</Text>
      <Text style={styles.text}>Height: {hp("50%")}</Text>
    </View>
  );
};

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

export default ResponsiveScreenExample;

Sử Dụng react-native-size-matters

Cài Đặt Thư Viện

bash Copy
npm install react-native-size-matters

Sử Dụng Thư Viện

javascript Copy
import React from "react";
import { View, Text, StyleSheet } from "react-native";
import { ScaledSheet, moderateScale } from "react-native-size-matters";

const SizeMattersExample = () => {
  return (
    <View style={styles.container}>
      <Text style={styles.text}>This is a responsive text</Text>
    </View>
  );
};

const styles = ScaledSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  text: {
    fontSize: "20@ms", // moderateScale(20)
  },
});

export default SizeMattersExample;

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

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ụ:

javascript Copy
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ụ:

javascript Copy
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 Dimensions Component

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

  1. Hiệu Suất: Khi sử dụng quá nhiều sự kiện lắng nghe thay đổi kích thước, hiệu suất của ứng dụng có thể bị ảnh hưởng.
  2. Tùy Chỉnh Giao Diện: Dimensions 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.
  3. 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.

Kết Luận

Dimensions 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 Dimensions, 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 Dimensions trong React Native và áp dụng vào các dự án của mình.

Avatar
Được viết bởi

Admin Team

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

Không có dữ liệu

Không có dữ liệu

Gợi ý bài viết
Không có dữ liệu

Không có dữ liệu

Bình luận

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

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