Cours React Native · Module 1: Ta première application
Boutons et interaction avec l'utilisateur
Dans cette leçon4
En Atlantide, chaque bouton est une porte vers une nouvelle fonctionnalité ! Apprenons différentes façons de gérer le toucher.
Pressable - Bouton moderne
Pressable est le composant le plus récent et le plus flexible pour gérer le toucher :
import { View, Text, Pressable, StyleSheet, Alert } from 'react-native';
export default function PressableExample() {
const handlePress = () => {
Alert.alert('Atlantide', 'Tu as découvert un secret des profondeurs !');
};
return (
<View style={styles.container}>
{/* Bouton de base */}
<Pressable
style={styles.button}
onPress={handlePress}
>
<Text style={styles.buttonText}>Appuie sur moi</Text>
</Pressable>
{/* Bouton avec effet d'appui */}
<Pressable
style={({ pressed }) => [
styles.button,
styles.primaryButton,
pressed && styles.buttonPressed,
]}
onPress={() => console.log('Pressed!')}
>
{({ pressed }) => (
<Text style={[styles.buttonText, pressed && styles.textPressed]}>
{pressed ? 'Appuyé !' : 'Appuie'}
</Text>
)}
</Pressable>
{/* Bouton désactivé */}
<Pressable
style={[styles.button, styles.disabledButton]}
disabled={true}
>
<Text style={[styles.buttonText, styles.disabledText]}>
Indisponible
</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
gap: 16,
backgroundColor: '#1a5276',
},
button: {
paddingVertical: 14,
paddingHorizontal: 28,
borderRadius: 8,
backgroundColor: '#2980b9',
minWidth: 200,
alignItems: 'center',
},
primaryButton: {
backgroundColor: '#27ae60',
},
buttonPressed: {
backgroundColor: '#1e8449',
transform: [{ scale: 0.98 }],
},
disabledButton: {
backgroundColor: '#7f8c8d',
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
textPressed: {
color: '#d5f5e3',
},
disabledText: {
color: '#bdc3c7',
},
});TouchableOpacity - Bouton avec effet d'opacité
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
export default function TouchableExample() {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.card}
activeOpacity={0.7} // Opacité lors de l'appui (0-1)
onPress={() => console.log('Card pressed')}
>
<Text style={styles.cardTitle}>Coquillage de la Sagesse</Text>
<Text style={styles.cardDescription}>
Touche pour découvrir le secret de l'océan
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.iconButton}
activeOpacity={0.6}
onPress={() => console.log('Heart pressed')}
>
<Text style={styles.icon}>J'aime</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
gap: 20,
backgroundColor: '#1a5276',
},
card: {
backgroundColor: '#2c3e50',
padding: 20,
borderRadius: 12,
width: '80%',
shadowColor: '#000',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
elevation: 5, // Ombre sur Android
},
cardTitle: {
fontSize: 18,
fontWeight: 'bold',
color: '#fff',
marginBottom: 8,
},
cardDescription: {
fontSize: 14,
color: '#bdc3c7',
},
iconButton: {
width: 60,
height: 60,
borderRadius: 30,
backgroundColor: '#e74c3c',
justifyContent: 'center',
alignItems: 'center',
},
icon: {
fontSize: 28,
},
});Gérer différents gestes
import { View, Text, Pressable, StyleSheet } from 'react-native';
import { useState } from 'react';
export default function GesturesExample() {
const [lastEvent, setLastEvent] = useState('En attente...');
return (
<View style={styles.container}>
<Text style={styles.status}>Dernier événement : {lastEvent}</Text>
<Pressable
style={styles.gestureArea}
onPress={() => setLastEvent('onPress - appui court')}
onLongPress={() => setLastEvent('onLongPress - appui long')}
onPressIn={() => console.log('Le doigt a touché l\'écran')}
onPressOut={() => console.log('Le doigt a quitté l\'écran')}
delayLongPress={500} // ms avant reconnaissance comme appui long
>
<Text style={styles.gestureText}>
Touche ou maintiens cette zone
</Text>
</Pressable>
<View style={styles.buttonRow}>
<Pressable
style={[styles.smallButton, styles.greenButton]}
onPress={() => setLastEvent('Oui !')}
>
<Text style={styles.smallButtonText}>Oui</Text>
</Pressable>
<Pressable
style={[styles.smallButton, styles.redButton]}
onPress={() => setLastEvent('Non !')}
>
<Text style={styles.smallButtonText}>Non</Text>
</Pressable>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
backgroundColor: '#1a5276',
},
status: {
fontSize: 16,
color: '#aed6f1',
marginBottom: 30,
textAlign: 'center',
},
gestureArea: {
width: '100%',
height: 150,
backgroundColor: '#2c3e50',
borderRadius: 12,
justifyContent: 'center',
alignItems: 'center',
borderWidth: 2,
borderColor: '#3498db',
borderStyle: 'dashed',
marginBottom: 30,
},
gestureText: {
fontSize: 16,
color: '#fff',
textAlign: 'center',
},
buttonRow: {
flexDirection: 'row',
gap: 20,
},
smallButton: {
paddingVertical: 12,
paddingHorizontal: 30,
borderRadius: 8,
},
greenButton: {
backgroundColor: '#27ae60',
},
redButton: {
backgroundColor: '#e74c3c',
},
smallButtonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});Alert - Fenêtres de dialogue
import { Alert, View, Pressable, Text, StyleSheet } from 'react-native';
export default function AlertExample() {
// Alerte simple
const showSimpleAlert = () => {
Alert.alert('L\'Atlantide dit', 'Bienvenue dans le monde sous-marin !');
};
// Alerte avec boutons
const showConfirmAlert = () => {
Alert.alert(
'Veux-tu continuer ?',
'Cette action t\'emmènera dans les profondeurs de l\'océan.',
[
{
text: 'Annuler',
style: 'cancel',
onPress: () => console.log('Canceled'),
},
{
text: 'Oui, je plonge !',
style: 'default',
onPress: () => console.log('Continuing'),
},
]
);
};
// Alerte destructive
const showDestructiveAlert = () => {
Alert.alert(
'Supprimer les données ?',
'Cette action est irréversible !',
[
{ text: 'Annuler', style: 'cancel' },
{ text: 'Supprimer', style: 'destructive', onPress: () => console.log('Deleted') },
]
);
};
return (
<View style={styles.container}>
<Pressable style={styles.button} onPress={showSimpleAlert}>
<Text style={styles.buttonText}>Alerte simple</Text>
</Pressable>
<Pressable style={styles.button} onPress={showConfirmAlert}>
<Text style={styles.buttonText}>Alerte de confirmation</Text>
</Pressable>
<Pressable style={[styles.button, styles.dangerButton]} onPress={showDestructiveAlert}>
<Text style={styles.buttonText}>Alerte destructive</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
gap: 16,
backgroundColor: '#1a5276',
},
button: {
backgroundColor: '#3498db',
paddingVertical: 14,
paddingHorizontal: 28,
borderRadius: 8,
minWidth: 220,
alignItems: 'center',
},
dangerButton: {
backgroundColor: '#e74c3c',
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});Code de cette leçon : App.tsx
import React from 'react';
import { View, Text, Pressable, StyleSheet, Alert } from 'react-native';
export default function App() {
const handlePress = () => {
Alert.alert('Atlantide', 'Tu as découvert un secret des profondeurs !');
};
return (
<View style={styles.container}>
{/* TODO : ajoute un <Pressable> avec onPress={handlePress} et style={styles.button} */}
{/* À l'intérieur du Pressable, place <Text style={styles.buttonText}>Clique ici</Text> */}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1a5276',
},
button: {
paddingVertical: 14,
paddingHorizontal: 28,
borderRadius: 8,
backgroundColor: '#2980b9',
},
buttonText: {
color: '#fff',
fontSize: 16,
fontWeight: '600',
},
});Entrées de la documentation utilisées dans cette leçon
Tu as repéré une erreur dans cette leçon ?
Teste tes connaissances
Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.
1. Quel composant est le plus récent et le plus flexible pour gérer le toucher ?
2. Comment s'appelle la prop pour gérer un clic en React Native (à la place de onClick) ?
Tâches pratiques dans le jeu
- Tri vertical
Remets dans le bon ordre les arguments de Alert.alert() :