Switch là một thành phần cơ bản trong React Native, được sử dụng để tạo ra các công tắc bật/tắt (toggle switch) cho các lựa chọn nhị phân (on/off, true/false). Switch thường được sử dụng trong các màn hình cài đặt, biểu mẫu, hoặc bất kỳ nơi nào cần người dùng chọn giữa hai trạng thái. Trong bài viết này, chúng ta sẽ tìm hiểu chi tiết về cách sử dụng Switch trong React Native, các thuộc tính và phương pháp tùy chỉnh, cùng với các ví dụ cụ thể.
Cú Pháp Cơ Bản
Để sử dụng Switch trong React Native, bạn cần import nó từ thư viện react-native và sử dụng nó như một thành phần trong ứng dụng của bạn.
            
            
              javascript
              
              
              
            
          
          import React, { useState } from "react";
import { View, Switch, StyleSheet } from "react-native";
const App = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled((previousState) => !previousState);
  return (
    <View style={styles.container}>
      <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});
export default App;
        Các Thuộc Tính Quan Trọng của Switch
value
Thuộc tính value xác định trạng thái hiện tại của Switch. Đây là một thuộc tính controlled component, nghĩa là giá trị của nó được kiểm soát bởi state và được cập nhật thông qua thuộc tính onValueChange.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <Switch value={isEnabled} onValueChange={setIsEnabled} />
        onValueChange
Thuộc tính onValueChange là một hàm callback được gọi khi người dùng thay đổi trạng thái của Switch. Nó nhận giá trị mới của Switch làm đối số.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <Switch onValueChange={(value) => console.log(value)} />
        trackColor
Thuộc tính trackColor cho phép bạn tùy chỉnh màu sắc của đường dẫn Switch. Nó nhận một đối tượng với hai thuộc tính false và true để xác định màu sắc khi Switch ở trạng thái tắt và bật.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <Switch trackColor={{ false: "#767577", true: "#81b0ff" }} />
        thumbColor
Thuộc tính thumbColor xác định màu sắc của nút Switch.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <Switch thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"} />
        ios_backgroundColor
Thuộc tính ios_backgroundColor xác định màu nền của Switch trên iOS khi Switch ở trạng thái tắt hoặc bị vô hiệu hóa.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <Switch ios_backgroundColor="#3e3e3e" />
        disabled
Thuộc tính disabled xác định liệu Switch có bị vô hiệu hóa hay không. Khi disabled là true, người dùng sẽ không thể thay đổi trạng thái của Switch.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <Switch disabled={true} />
        Ví Dụ Chi Tiết về Switch
Ví Dụ 1: Tạo Switch Cơ Bản
            
            
              javascript
              
              
              
            
          
          import React, { useState } from "react";
import { View, Switch, StyleSheet, Text } from "react-native";
const BasicSwitch = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled((previousState) => !previousState);
  return (
    <View style={styles.container}>
      <Text>{isEnabled ? "Switch is ON" : "Switch is OFF"}</Text>
      <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});
export default BasicSwitch;
        Ví Dụ 2: Tạo Switch với Màu Sắc Tùy Chỉnh
            
            
              javascript
              
              
              
            
          
          import React, { useState } from "react";
import { View, Switch, StyleSheet, Text } from "react-native";
const CustomColorSwitch = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled((previousState) => !previousState);
  return (
    <View style={styles.container}>
      <Text>{isEnabled ? "Switch is ON" : "Switch is OFF"}</Text>
      <Switch
        trackColor={{ false: "#d3d3d3", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#ff6347" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={toggleSwitch}
        value={isEnabled}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});
export default CustomColorSwitch;
        Ví Dụ 3: Tạo Switch Bị Vô Hiệu Hóa
            
            
              javascript
              
              
              
            
          
          import React, { useState } from "react";
import { View, Switch, StyleSheet, Text } from "react-native";
const DisabledSwitch = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  return (
    <View style={styles.container}>
      <Text>{isEnabled ? "Switch is ON" : "Switch is OFF"}</Text>
      <Switch
        trackColor={{ false: "#767577", true: "#81b0ff" }}
        thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
        ios_backgroundColor="#3e3e3e"
        onValueChange={() => {}}
        value={isEnabled}
        disabled={true}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});
export default DisabledSwitch;
        Tùy Chỉnh Switch với Các Thư Viện Bên Ngoài
Sử Dụng react-native-switch
react-native-switch là một thư viện cung cấp các thành phần Switch tùy chỉnh với nhiều tùy chọn hơn so với Switch mặc định của React Native.
Cài Đặt Thư Viện
            
            
              bash
              
              
              
            
          
          npm install react-native-switch
        Sử Dụng react-native-switch
Ví dụ:
            
            
              javascript
              
              
              
            
          
          import React, { useState } from "react";
import { View, StyleSheet } from "react-native";
import { Switch } from "react-native-switch";
const CustomSwitch = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  return (
    <View style={styles.container}>
      <Switch
        value={isEnabled}
        onValueChange={(val) => setIsEnabled(val)}
        disabled={false}
        activeText={"On"}
        inActiveText={"Off"}
        circleSize={30}
        barHeight={1}
        circleBorderWidth={3}
        backgroundActive={"green"}
        backgroundInactive={"gray"}
        circleActiveColor={"#30a566"}
        circleInActiveColor={"#000000"}
        changeValueImmediately={true}
        innerCircleStyle={{ alignItems: "center", justifyContent: "center" }}
        outerCircleStyle={{}}
        renderActiveText={false}
        renderInActiveText={false}
        switchLeftPx={2}
        switchRightPx={2}
        switchWidthMultiplier={2}
        switchBorderRadius={30}
      />
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "center",
  },
});
export default CustomSwitch;
        Hình ảnh minh họa:
Custom Switch with react-native-switch
Tạo Switch Tùy Chỉnh
Đôi khi, bạn có thể cần tạo một thành phần Switch tùy chỉnh để phù hợp với thiết kế hoặc chức năng cụ thể của ứng dụng. Dưới đây là cách tạo một thành phần Switch tùy chỉnh sử dụng TouchableOpacity và Animated.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          import React, { useState } from "react";
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  Animated,
} from "react-native";
const CustomToggleSwitch = () => {
  const [isEnabled, setIsEnabled] = useState(false);
  const [animatedValue] = useState(new Animated.Value(isEnabled ? 1 : 0));
  const toggleSwitch = () => {
    setIsEnabled((previousState) => !previousState);
    Animated.timing(animatedValue, {
      toValue: isEnabled ? 0 : 1,
      duration: 300,
      useNativeDriver: false,
    }).start();
  };
  const translateX = animatedValue.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 24],
  });
  return (
    <TouchableOpacity onPress={toggleSwitch} style={styles.switchContainer}>
      <Animated.View style={[styles.switch, { transform: [{ translateX }] }]}>
        <Text style={styles.switchText}>{isEnabled ? "ON" : "OFF"}</Text>
      </Animated.View>
    </TouchableOpacity>
  );
};
const styles = StyleSheet.create({
  switchContainer: {
    width: 56,
    height: 32,
    borderRadius: 16,
    backgroundColor: "#ccc",
    justifyContent: "center",
    padding: 4,
  },
  switch: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: "#fff",
    justifyContent: "center",
    alignItems: "center",
  },
  switchText: {
    fontSize: 10,
    color: "#000",
  },
});
export default CustomToggleSwitch;
        Các Kỹ Thuật Tối Ưu Hóa Sử Dụng Switch
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
              
              
              
            
          
          const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  switchContainer: {
    width: 56,
    height: 32,
    borderRadius: 16,
    backgroundColor: "#ccc",
    justifyContent: "center",
    padding: 4,
  },
  switch: {
    width: 24,
    height: 24,
    borderRadius: 12,
    backgroundColor: "#fff",
    justifyContent: "center",
    alignItems: "center",
  },
  switchText: {
    fontSize: 10,
    color: "#000",
  },
});
        Sử Dụng Inline Styles cho Các Thành Phần Đơn Giản
Đối với các thành phần đơn giản hoặc khi bạn cần thay đổi style động, bạn có thể sử dụng inline styles.
Ví dụ:
            
            
              javascript
              
              
              
            
          
          <TouchableOpacity
  style={{ backgroundColor: "blue", padding: 10, borderRadius: 5 }}
/>
        Các Hạn Chế của Switch Component
Mặc dù Switch component trong React Native rất mạnh mẽ, nhưng nó cũng có một số hạn chế:
- Tùy Chỉnh Giao Diện: 
Switchcomponent 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. - Hiệu Suất: Khi sử dụng quá nhiều 
Switchlồng nhau, hiệu suất của ứng dụng có thể bị ảnh hưởng. - Khả Năng Tái Sử Dụng: Việc sử dụng inline styles có thể làm giảm khả năng tái sử dụng các thành phần.
 
Kết Luận
Switch 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 Switch, 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 Switch trong React Native và áp dụng vào các dự án của mình.