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

Hiển thị Dropdown (Picker) trong React Native


Picker** là component tích hợp sẵn của React Native để chọn một giá trị từ danh sách (dropdown/spinner). Tuy nhiên, Picker core đã **deprecated** từ RN 0.64+, khuyên dùng @react-native-picker/picker (community maintained).

Cài đặt (Khuyên dùng)

npm install @react-native-picker/picker

npx pod-install (iOS).

Import

// Cách mới (package riêng)
import { Picker } from '@react-native-picker/picker';

// Cách cũ (core - deprecated)
import { Picker } from 'react-native';

Cú pháp cơ bản

<Picker
  selectedValue={selectedValue}
  onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}
  mode="dropdown"        // 'dialog' | 'dropdown' (Android)
  itemStyle={styles.item}
  enabled={true}
>
  <Picker.Item label="Option 1" value="value1" />
  <Picker.Item label="Option 2" value="value2" />
  <Picker.Item label="Option 3" value="value3" />
</Picker>

Props chính

PropKiểuMô tả
selectedValueanyGiá trị đang chọn (match với value của Picker.Item).
onValueChangefunc(value, index) => void. Gọi khi user chọn item mới.
modeenumAndroid: 'dialog' (modal), 'dropdown' (spinner inline). iOS: chỉ 'dialog'.
enabledbooleanVô hiệu hóa picker.
itemStyleobjectStyle cho từng item text.
dropdownIconRtlbooleanĐảo icon mũi tên (RTL).
styleobjectStyle container picker.

Ví dụ 1: Picker cơ bản (Dropdown mode)

import React, { useState } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Picker } from '@react-native-picker/picker';

const PickerExample = () => {
  const [user, setUser] = useState('');

  return (
    
      
        
        
        
      
      Đã chọn: {user || 'Chưa chọn'}
    
  );
};

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', padding: 20 },
  picker: { height: 50, width: '100%' },
  item: { fontSize: 16 },
  selectedText: { marginTop: 20, fontSize: 18, fontWeight: 'bold', textAlign: 'center' },
});

export default PickerExample;

Ví dụ 2: Picker từ mảng dữ liệu động

const COUNTRIES = [
  { code: 'VN', name: 'Việt Nam' },
  { code: 'US', name: 'Hoa Kỳ' },
  { code: 'JP', name: 'Nhật Bản' },
  { code: 'KR', name: 'Hàn Quốc' },
];

const CountryPicker = () => {
  const [country, setCountry] = useState('');

  return (
    
      {COUNTRIES.map(c => (
        
      ))}
    
  );
};

Ví dụ 3: Custom Dropdown UI (Thay thế Picker)

Picker native khó custom UI (màu nền, border, icon, animation). Thường dùng thư viện hoặc tự xây:

  • react-native-select-dropdown - Phổ biến, customizable.
  • react-native-modal-dropdown - Dùng Modal.
  • Tự viết với Pressable + Modal/FlatList - Kiểm soát hoàn toàn.
// Ví dụ ý tưởng custom dropdown đơn giản
import React, { useState } from 'react';
import { View, Text, Pressable, StyleSheet, FlatList, Modal } from 'react-native';

const CustomDropdown = ({ options, value, onChange, placeholder }) => {
  const [open, setOpen] = useState(false);
  const selected = options.find(o => o.value === value);

  return (
    
       setOpen(!open)}>
        {selected?.label || placeholder}
        {open ? '▲' : '▼'}
      
       setOpen(false)}>
         true}>
          
             o.value}
              renderItem={({ item }) => (
                 { onChange(item.value); setOpen(false); }}
                  style={styles.option}
                >
                  
                    {item.label}
                  
                
              )}
            />
          
        
      
    
  );
};

Lưu ý quan trọng

  • Picker core (react-native) **đã deprecated**, sẽ bị xóa trong tương lai. **Luôn dùng @react-native-picker/picker**.
  • Android: mode="dropdown" hiển thị inline spinner, mode="dialog" hiển thị modal fullscreen.
  • iOS: Chỉ hỗ trợ mode="dialog" (modal từ dưới trượt lên).
  • Để UI nhất quán cross-platform, khuyên dùng custom dropdown hoặc thư viện.
  • Accessibility: Thêm accessibilityLabel, accessibilityRole="combobox".