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

Xử lý sự kiện chạm (Touch) trong React Native


Trên thiết bị di động, tương tác chủ yếu qua chạm (tap), vuốt (swipe), zoom. React Native cung cấp nhiều cách xử lý: event onPress trên component có sẵn, và các **Touchable components** cho view tùy chỉnh.

1. Button - Cách đơn giản nhất

import { Button, View } from 'react-native';

2. Touchable Components (Dành cho View tùy chỉnh)

Khi cần bấm vào View, Image, Text tự thiết kế, dùng 3 component:

ComponentHiệu ứngPhù hợp
TouchableOpacityLàm mờ (opacity giảm) khi bấmNút bấm tùy chỉnh, item danh sách
TouchableHighlightLàm tối màu nền (underlay) khi bấmNút có màu nền rõ ràng
TouchableWithoutFeedbackKhông có hiệu ứng thị giácKhi không muốn feedback, hoặc tự handle animation

TouchableOpacity - Phổ biến nhất

import React from 'react';
import { TouchableOpacity, Text, StyleSheet, View } from 'react-native';

const App = () => (
  
     alert('Bạn chạm vào tôi!')}
      activeOpacity={0.7} // Độ mờ khi bấm (0-1, mặc định 0.2)
    >
      Nút tùy chỉnh
    
  
);

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', alignItems: 'center' },
  buttonText: {
    borderWidth: 1,
    padding: 15,
    borderColor: 'black',
    backgroundColor: 'red',
    color: 'white',
    fontSize: 18,
  },
});

export default App;

TouchableHighlight - Hiệu ứng "nhấn xuống"

import { TouchableHighlight, Text, StyleSheet, View } from 'react-native';

 alert('Chạm!')} 
  underlayColor="gray" // Màu khi bấm
  activeOpacity={0.6}
>
  Nút Highlight

TouchableWithoutFeedback - Không feedback

import { TouchableWithoutFeedback, Text, StyleSheet, View } from 'react-native';

 alert('Chạm!')}>
  Nút không hiệu ứng

3. Pressable (React Native 0.63+) - API mới, mạnh hơn

Pressable thay thế dần các Touchable cũ, hỗ trợ:

  • onPressIn, onPressOut, onLongPress.
  • Props style nhận function: ({ pressed }) => ({ opacity: pressed ? 0.5 : 1 }).
  • Hỗ trợ android_ripple cho hiệu ứng Material Design.
import { Pressable, Text, StyleSheet } from 'react-native';

 alert('Pressable!')}
  style={({ pressed }) => [
    styles.button,
    { backgroundColor: pressed ? '#ccc' : '#007AFF' }
  ]}
  android_ripple={{ color: 'rgba(0,0,0,0.2)' }}
>
  Pressable Button

So sánh nhanh

Tình huốngKhuyên dùng
Nút chuẩn Material/iOSButton hoặc Pressable
Custom UI, cần hiệu ứng nhấnTouchableOpacity hoặc Pressable
Cần hiệu ứng ripple AndroidPressable + android_ripple
Không muốn hiệu ứng nàoTouchableWithoutFeedback
Long press (giữ lâu)Pressable (onLongPress) hoặc TouchableOpacity (delayLongPress)

Mẹo tránh lỗi thường gặp

  • Không bọc Touchable* quanh ScrollView/FlatList (gây conflict scroll).
  • Dùng hitSlop mở rộng vùng chạm: hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}.
  • Trên Android, TouchableNativeFeedback (deprecated) cho ripple thật sự, thay bằng Pressable.