Touchable Components
Glissez pour afficher le menu
React Native provides several built-in components for handling touch interactions. One of the most commonly used is TouchableOpacity, which allows users to interact with elements such as buttons, cards, and icons.
When a user presses a TouchableOpacity component, its opacity decreases slightly, creating visual feedback that indicates the touch was registered. This makes it a simple and effective way to build interactive mobile interfaces.
TouchableOpacity accepts an onPress prop, which is a function that runs when the user taps the component. You can place any React Native elements inside it, including Text, View, or Image components.
React Native also includes other touchable components, such as TouchableHighlight, which provides feedback by displaying a highlight color behind the wrapped element when pressed. However, TouchableOpacity is often the preferred choice for simple buttons and user interactions.
The example below creates a button that changes opacity when pressed and displays an alert message.
import React from 'react';
import {
View,
Text,
TouchableOpacity,
StyleSheet,
Alert,
} from 'react-native';
export default function App() {
const handlePress = () => {
Alert.alert('Button Pressed', 'You tapped the button.');
};
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
activeOpacity={0.6}
onPress={handlePress}
>
<Text style={styles.buttonText}>Press Me</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
backgroundColor: '#007AFF',
paddingVertical: 12,
paddingHorizontal: 24,
borderRadius: 8,
},
buttonText: {
color: '#FFFFFF',
fontSize: 18,
},
});
In this example, TouchableOpacity wraps a Text component and acts as a button. The activeOpacity property controls how transparent the button becomes while pressed. When the user taps the button, the onPress function runs and displays an alert message.
Merci pour vos commentaires !
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion