Khóa học react-native

Linking trong React Native

0 phút đọc

Linking là một module trong React Native cho phép bạn xử lý các liên kết (links) và URL. Nó cung cấp các phương thức để mở các URL trong trình duyệt web, ứng dụng khác, hoặc thậm chí là trong chính ứng dụng của bạn. Linking cũng cho phép bạn lắng nghe các sự kiện khi người dùng mở ứng dụng thông qua một liên kết cụ thể, giúp bạn có thể xử lý các deep link và dynamic link.

Cú Pháp Cơ Bản

Để sử dụng Linking 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ó để xử lý các liên kết.

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

const App = () => {
  const openURL = () => {
    Linking.openURL("https://reactnative.dev");
  };

  return (
    <View style={styles.container}>
      <Button title="Open React Native Website" onPress={openURL} />
    </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 Linking

openURL

Phương thức openURL được sử dụng để mở một URL trong trình duyệt web hoặc ứng dụng khác. Nó nhận vào một tham số là URL cần mở.

Cú pháp:

Linking.openURL(url);

Ví dụ:

Linking.openURL("https://reactnative.dev");

canOpenURL

Phương thức canOpenURL được sử dụng để kiểm tra xem một URL có thể được mở hay không. Nó trả về một Promise với giá trị boolean.

Cú pháp:

Linking.canOpenURL(url);

Ví dụ:

Linking.canOpenURL("https://reactnative.dev").then((supported) => {
  if (supported) {
    Linking.openURL("https://reactnative.dev");
  } else {
    console.log("Don't know how to open URI: " + url);
  }
});

addEventListener

Phương thức addEventListener được sử dụng để lắng nghe các sự kiện liên quan đến liên kết. Nó nhận vào hai tham số: tên sự kiện (url) và một hàm callback để xử lý sự kiện.

Cú pháp:

Linking.addEventListener(eventName, handler);

Ví dụ:

Linking.addEventListener("url", handleOpenURL);

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:

Linking.removeEventListener(eventName, handler);

Ví dụ:

Linking.removeEventListener("url", handleOpenURL);

getInitialURL

Phương thức getInitialURL được sử dụng để lấy URL ban đầu mà ứng dụng được mở. Nó trả về một Promise với URL hoặc null nếu không có URL nào.

Cú pháp:

Linking.getInitialURL();

Ví dụ:

Linking.getInitialURL().then((url) => {
  if (url) {
    console.log("Initial URL is: " + url);
  }
});

Ví Dụ Chi Tiết về Linking

Ví Dụ 1: Mở URL trong Trình Duyệt Web

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

const OpenURLExample = () => {
  const openURL = () => {
    Linking.openURL("https://reactnative.dev");
  };

  return (
    <View style={styles.container}>
      <Button title="Open React Native Website" onPress={openURL} />
    </View>
  );
};

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

export default OpenURLExample;

Ví Dụ 2: Kiểm Tra và Mở URL

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

const CheckAndOpenURLExample = () => {
  const openURL = (url) => {
    Linking.canOpenURL(url).then((supported) => {
      if (supported) {
        Linking.openURL(url);
      } else {
        Alert.alert("Don't know how to open URI: " + url);
      }
    });
  };

  return (
    <View style={styles.container}>
      <Button
        title="Open React Native Website"
        onPress={() => openURL("https://reactnative.dev")}
      />
    </View>
  );
};

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

export default CheckAndOpenURLExample;

Ví Dụ 3: Lắng Nghe Sự Kiện URL

import React, { useEffect } from "react";
import { View, Text, Linking, StyleSheet } from "react-native";

const URLListenerExample = () => {
  useEffect(() => {
    const handleOpenURL = (event) => {
      console.log("URL:", event.url);
    };

    Linking.addEventListener("url", handleOpenURL);

    return () => {
      Linking.removeEventListener("url", handleOpenURL);
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text>Listening for URL events...</Text>
    </View>
  );
};

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

export default URLListenerExample;

Tùy Chỉnh Linking

Sử Dụng Linking với Deep Linking

Deep linking cho phép bạn mở ứng dụng của mình từ một liên kết URL cụ thể. Điều này rất hữu ích cho việc điều hướng người dùng đến các phần cụ thể của ứng dụng từ bên ngoài.

Ví dụ:

import React, { useEffect } from "react";
import { View, Text, Linking, StyleSheet } from "react-native";

const DeepLinkingExample = () => {
  useEffect(() => {
    const handleOpenURL = (event) => {
      const url = event.url;
      console.log("Deep link URL:", url);
      // Xử lý URL để điều hướng trong ứng dụng
    };

    Linking.addEventListener("url", handleOpenURL);

    return () => {
      Linking.removeEventListener("url", handleOpenURL);
    };
  }, []);

  return (
    <View style={styles.container}>
      <Text>Listening for deep link events...</Text>
    </View>
  );
};

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

export default DeepLinkingExample;

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-navigation để xử lý deep linking và điều hướng.

Sử Dụng react-navigation

Cài Đặt Thư Viện

npm install @react-navigation/native
npm install @react-navigation/stack
npm install react-native-screens react-native-safe-area-context

Sử Dụng Thư Viện

import React, { useEffect } from "react";
import { View, Text, Button, Linking, StyleSheet } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";

const HomeScreen = ({ navigation }) => {
  return (
    <View style={styles.container}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => navigation.navigate("Details")}
      />
    </View>
  );
};

const DetailsScreen = () => {
  return (
    <View style={styles.container}>
      <Text>Details Screen</Text>
    </View>
  );
};

const Stack = createStackNavigator();

const App = () => {
  useEffect(() => {
    const handleOpenURL = (event) => {
      const url = event.url;
      console.log("Deep link URL:", url);
      // Xử lý URL để điều hướng trong ứng dụng
    };

    Linking.addEventListener("url", handleOpenURL);

    return () => {
      Linking.removeEventListener("url", handleOpenURL);
    };
  }, []);

  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="Details" component={DetailsScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
};

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

export default App;

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

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 openURL = () => {
  Linking.openURL("https://reactnative.dev");
};

<Button title="Open React Native Website" onPress={openURL} />;

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

Mặc dù Linking 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 URL, hiệu suất của ứng dụng có thể bị ảnh hưởng.
  2. Tùy Chỉnh Giao Diện: Linking 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

Linking 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 Linking, 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 Linking 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