Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีแสดง Checkbox ใน React Native


Checkbox เป็นคอมโพเนนต์ทั่วไปที่ใช้บน UI บ่อย React Native core ไม่มี checkbox ต้องติดตั้งแพ็กเกจ

การติดตั้ง

npm install --save-dev react-native-paper

คอมโพเนนต์พื้นฐาน

<Checkbox status={checkboxStatus} onPress={onCheckboxCheckedFunc} />

คุณสมบัติสำคัญ

Props คำอธิบาย
status ค่า: 'checked', 'unchecked', 'indeterminate'
disabled boolean เปิด/ปิดการใช้งาน
onPress ฟังก์ชันเรียกเมื่อ checkbox ถูกเช็ค
color สีของ checkbox
uncheckColor สีของ checkbox ในสถานะ unchecked

ตัวอย่าง: แสดง Checkbox

ใช้ useState จัดการสถานะ checked/unchecked:

const [checked, setChecked] = React.useState(false);

อัปเดตสถานะเมื่อผู้ใช้เช็ค/ยกเลิก:

onPress={() => {
  setChecked(!checked);
}}

โค้ดเต็มรูปแบบ

import * as React from 'react';
import { StyleSheet, Text, SafeAreaView } from 'react-native';
import { Checkbox } from 'react-native-paper';

const MyComponent = () => {
  const [checked, setChecked] = React.useState(false);

  return (
    
       {
          setChecked(!checked);
        }}
        color={'green'}
        uncheckColor={'red'}
      />
      Checkbox
    
  );
};

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

export default MyComponent;

ผลลัพธ์

วิธีแสดง Checkbox ใน React Native

ตัวเลือกอื่น

  • @react-native-community/checkbox - คอมโพเนนต์ checkbox อย่างเป็นทางการจากชุมชน
  • สร้าง custom checkbox เองด้วย TouchableOpacity + Icon