In React Native, handling touches can be done using various components like TouchableOpacity, TouchableHighlight, TouchableWithoutFeedback, and TouchableNativeFeedback.
- TouchableOpacity: This component provides an opacity effect when pressed. It is often used for buttons and other touchable elements.
Example:
<TouchableOpacity onPress={() => alert('Button pressed')}>
<View style={styles.button}>
<Text style={styles.buttonText}>Press me</Text>
</View>
</TouchableOpacity>
- TouchableHighlight: This component provides a highlight effect when pressed. It is often used for buttons and other touchable elements.
Example:
<TouchableHighlight onPress={() => alert('Button pressed')}>
<View style={styles.button}>
<Text style={styles.buttonText}>Press me</Text>
</View>
</TouchableHighlight>
- TouchableWithoutFeedback: This component does not provide any feedback when pressed. It is often used for handling gestures like swipes and pinches.
Example:
<TouchableWithoutFeedback onPress={() => alert('Button pressed')}>
<View style={styles.button}>
<Text style={styles.buttonText}>Press me</Text>
</View>
</TouchableWithoutFeedback>
- TouchableNativeFeedback: This component provides a ripple effect when pressed on Android devices. It is often used for buttons and other touchable elements.
Example:
<TouchableNativeFeedback onPress={() => alert('Button pressed')}>
<View style={styles.button}>
<Text style={styles.buttonText}>Press me</Text>
</View>
</TouchableNativeFeedback>
Each of these components accepts an onPress function that will be executed when the component is pressed. In the above examples, we are using an anonymous function to show an alert when the button is pressed.
In addition to onPress, these components also accept various other props like onLongPress, delayLongPress, and pressRetentionOffset, which can be used to customize the touch handling behavior.