Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Hiển thị Checkbox trong React Native với react-native-paper


React Native core **không có** component Checkbox tích hợp. Cách phổ biến nhất là dùng react-native-paper (Material Design) hoặc @react-native-community/checkbox (core community). Bài viết tập trung vào react-native-paper.

Cài đặt

npm install react-native-paper

npx pod-install (iOS).

Import

import { Checkbox } from 'react-native-paper';

Cú pháp cơ bản

<Checkbox
  status={checked ? 'checked' : 'unchecked'} // 'checked' | 'unchecked' | 'indeterminate'
  onPress={() => setChecked(!checked)}
  color="#4CAF50"
  uncheckColor="#9E9E9E"
/>

Các props chính

PropKiểuMô tả
statusenum'checked', 'unchecked', 'indeterminate' (trạng thái một phần).
onPressfuncCallback khi bấm (toggle).
colorstringMàu khi checked (mặc định theme primary).
uncheckColorstringMàu viền khi unchecked.
disabledbooleanVô hiệu hóa.
sizenumberKích thước (mặc định 24).

Ví dụ cơ bản: Checkbox đơn lẻ

import * as React from 'react';
import { StyleSheet, SafeAreaView, Text } 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' },
  label: { marginTop: 10, fontSize: 16 },
});

export default MyComponent;

Ví dụ nâng cao: Danh sách checkbox (Todo list)

import React, { useState } from 'react';
import { View, StyleSheet, FlatList, Text } from 'react-native';
import { Checkbox } from 'react-native-paper';

const TODO_ITEMS = [
  { id: '1', text: 'Học React Native' },
  { id: '2', text: 'Viết blog' },
  { id: '3', text: 'Deploy app' },
];

const TodoList = () => {
  const [completed, setCompleted] = useState(new Set());

  const toggle = (id) => {
    setCompleted(prev => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };

  const renderItem = ({ item }) => (
    
       toggle(item.id)}
        color="#2196F3"
      />
      
        {item.text}
      
    
  );

  return (
    
       item.id}
        ItemSeparatorComponent={() => }
      />
    
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, padding: 16 },
  row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 12 },
  itemText: { marginLeft: 12, fontSize: 16 },
  completed: { textDecorationLine: 'line-through', color: '#999' },
  separator: { borderBottomWidth: 1, borderColor: '#eee' },
});

export default TodoList;

Ví dụ 3: Indeterminate (Checkbox cha - chọn tất cả/con)

import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { Checkbox } from 'react-native-paper';

const ParentCheckbox = () => {
  const [children, setChildren] = useState([
    { id: 1, label: 'Option A', checked: false },
    { id: 2, label: 'Option B', checked: true },
    { id: 3, label: 'Option C', checked: false },
  ]);

  const allChecked = children.every(c => c.checked);
  const someChecked = children.some(c => c.checked);
  const parentStatus = allChecked ? 'checked' : someChecked ? 'indeterminate' : 'unchecked';

  const toggleAll = () => {
    setChildren(prev => prev.map(c => ({ ...c, checked: !allChecked })));
  };

  const toggleChild = (id) => {
    setChildren(prev => prev.map(c => c.id === id ? { ...c, checked: !c.checked } : c));
  };

  return (
    
      
        
        Chọn tất cả
      
      {children.map(c => (
        
           toggleChild(c.id)}
            color="#2196F3"
          />
          {c.label}
        
      ))}
    
  );
};

const styles = StyleSheet.create({
  container: { padding: 16 },
  row: { flexDirection: 'row', alignItems: 'center', paddingVertical: 8 },
  label: { marginLeft: 12, fontSize: 16 },
});

export default ParentCheckbox;

Alternative: @react-native-community/checkbox

Nếu muốn component nhẹ hơn, dùng package chính thức của community:

npm install @react-native-community/checkbox
import CheckBox from '@react-native-community/checkbox';

Lưu ý: UI đơn giản hơn, ít tùy biến hơn Paper.