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:
| Component | Hiệu ứng | Phù hợp |
|---|---|---|
TouchableOpacity | Làm mờ (opacity giảm) khi bấm | Nút bấm tùy chỉnh, item danh sách |
TouchableHighlight | Làm tối màu nền (underlay) khi bấm | Nút có màu nền rõ ràng |
TouchableWithoutFeedback | Không có hiệu ứng thị giác | Khi 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
stylenhận function:({ pressed }) => ({ opacity: pressed ? 0.5 : 1 }). - Hỗ trợ
android_ripplecho 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ống | Khuyên dùng |
|---|---|
| Nút chuẩn Material/iOS | Button hoặc Pressable |
| Custom UI, cần hiệu ứng nhấn | TouchableOpacity hoặc Pressable |
| Cần hiệu ứng ripple Android | Pressable + android_ripple |
| Không muốn hiệu ứng nào | TouchableWithoutFeedback |
| 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*quanhScrollView/FlatList(gây conflict scroll). - Dùng
hitSlopmở 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ằngPressable.