RN Lez 06: State, Eventi e TextInput
Docs: State, Handling Text Input
Obiettivi
Section titled “Obiettivi”- Usare useState per gestire dati che cambiano
- Gestire eventi: onPress, onChangeText
- Usare TextInput e Button
1. useState — lo stato
Section titled “1. useState — lo stato”useState permette a un componente di ricordare dati che cambiano.
import { useState } from 'react';
const Contatore = () => { const [count, setCount] = useState(0); // ↑ ↑ ↑ // LEGGO SCRIVO INIZIALE
return ( <View> <Text>Hai cliccato {count} volte</Text> <Button title="+1" onPress={() => setCount(count + 1)} /> </View> );};Come funziona
Section titled “Come funziona”useState(0)→ creacount= 0setCount(count + 1)→ aggiorna il valore- React ri-renderizza il componente con il nuovo valore
Regole
Section titled “Regole”// ✅ Correttoconst [nome, setNome] = useState('Mario');
// ❌ NON modificare direttamentenome = 'Luigi'; // la UI NON si aggiorna!
// ✅ USA setNomesetNome('Luigi'); // la UI si aggiorna2. Button e onPress
Section titled “2. Button e onPress”import { Button } from 'react-native';
<Button title="Cliccami" onPress={funzione} // funzione da chiamare color="blue" // colore (Android) disabled={false} // disabilitato?/>Tre modi di scrivere handler
Section titled “Tre modi di scrivere handler”// 1. Funzione esterna (leggibile)const incrementa = () => setCount(count + 1);<Button title="+1" onPress={incrementa} />
// 2. Arrow inline (semplice)<Button title="+1" onPress={() => setCount(count + 1)} />
// 3. ❌ ERRORE: chiamata diretta (esegue SUBITO!)<Button title="+1" onPress={setCount(count + 1)} />3. TextInput — campo di input
Section titled “3. TextInput — campo di input”import { TextInput } from 'react-native';
const FormNome = () => { const [nome, setNome] = useState('');
return ( <View> <TextInput style={styles.input} placeholder="Il tuo nome" value={nome} onChangeText={setNome} // (text) => setNome(text) /> <Text>Ciao, {nome}!</Text> </View> );};
const styles = StyleSheet.create({ input: { borderWidth: 1, borderColor: '#ccc', padding: 12, borderRadius: 8, fontSize: 16, marginBottom: 10, },});Proprietà TextInput
Section titled “Proprietà TextInput”| Proprietà | Descrizione | Esempio |
|---|---|---|
value | Valore controllato | value={nome} |
onChangeText | Chiamata quando cambia | onChangeText={setNome} |
placeholder | Testo suggerimento | placeholder="Nome..." |
secureTextEntry | Password | secureTextEntry={true} |
keyboardType | Tipo tastiera | keyboardType="numeric" |
multiline | Multi riga | multiline={true} |
4. Alert — messaggi e conferme
Section titled “4. Alert — messaggi e conferme”import { Alert } from 'react-native';
// SempliceAlert.alert('Messaggio', 'Ciao mondo!');
// Con bottoneAlert.alert('Successo', 'Operazione completata', [ { text: 'OK' }]);
// Con sceltaAlert.alert( 'Elimina', 'Sei sicuro?', [ { text: 'Annulla', style: 'cancel' }, { text: 'Elimina', style: 'destructive', onPress: () => elimina() }, ]);5. Esempio: Form presentazione
Section titled “5. Esempio: Form presentazione”import { useState } from 'react';import { View, Text, TextInput, Button, Alert, StyleSheet } from 'react-native';
export default function App() { const [nome, setNome] = useState(''); const [eta, setEta] = useState('');
const invia = () => { if (!nome || !eta) { Alert.alert('Errore', 'Compila tutti i campi!'); return; } Alert.alert('✅ Ricevuto', `Ciao ${nome}, ${eta} anni!`); };
return ( <View style={styles.container}> <Text style={styles.titolo}>Chi sei?</Text> <TextInput style={styles.input} placeholder="Nome" value={nome} onChangeText={setNome} /> <TextInput style={styles.input} placeholder="Età" value={eta} onChangeText={setEta} keyboardType="numeric" /> <Button title="Invia" onPress={invia} /> </View> );}6. Tabella riassuntiva
Section titled “6. Tabella riassuntiva”| Concetto | Codice |
|---|---|
| useState | const [x, setX] = useState(0) |
| Aggiornare | setX(nuovoValore) |
| Button | <Button title="..." onPress={fn} /> |
| TextInput | <TextInput value={x} onChangeText={setX} /> |
| Alert | Alert.alert('Titolo', 'Msg') |
7. Esercizio
Section titled “7. Esercizio”🎯 “Convertitore € → $”
Section titled “🎯 “Convertitore € → $””Crea un’app che:
- Campo per importo in euro
- Campo per tasso di cambio (default 1.08)
- Bottone “Converti”
- Mostra
X.XX € = Y.YY $ - Se importo vuoto → Alert di errore