Kurs React Native · Moduł 1: Pierwsza aplikacja

TextInput - pola tekstowe

4 min czytania ·
W tej lekcji4

W Atlantydzie komunikacja jest kluczowa! Nauczmy się odbierać tekst od użytkowników.

Podstawowy TextInput

import { SafeAreaView, View, Text, TextInput, StyleSheet } from 'react-native';
import { useState } from 'react';

export default function TextInputExample() {
  const [name, setName] = useState('');
  const [message, setMessage] = useState('');

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.title}>Wiadomość do Posejdona</Text>

      {/* Podstawowe pole tekstowe */}
      <View style={styles.inputGroup}>
        <Text style={styles.label}>Twoje imię</Text>
        <TextInput
          style={styles.input}
          value={name}
          onChangeText={setName}
          placeholder="Wpisz swoje imię..."
          placeholderTextColor="#7f8c8d"
        />
      </View>

      {/* Wieloliniowe pole tekstowe */}
      <View style={styles.inputGroup}>
        <Text style={styles.label}>Wiadomość</Text>
        <TextInput
          style={[styles.input, styles.textArea]}
          value={message}
          onChangeText={setMessage}
          placeholder="Napisz wiadomość do władcy mórz..."
          placeholderTextColor="#7f8c8d"
          multiline={true}
          numberOfLines={4}
          textAlignVertical="top"
        />
      </View>

      {/* Podgląd */}
      <View style={styles.preview}>
        <Text style={styles.previewText}>
          {name ? `Od: ${name}` : 'Podaj swoje imię'}
        </Text>
        <Text style={styles.previewMessage}>
          {message || 'Napisz wiadomość...'}
        </Text>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 24,
    textAlign: 'center',
  },
  inputGroup: {
    marginBottom: 16,
  },
  label: {
    fontSize: 14,
    color: '#aed6f1',
    marginBottom: 8,
    fontWeight: '500',
  },
  input: {
    backgroundColor: '#2c3e50',
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: '#fff',
    borderWidth: 1,
    borderColor: '#34495e',
  },
  textArea: {
    minHeight: 100,
  },
  preview: {
    backgroundColor: '#2c3e50',
    borderRadius: 12,
    padding: 16,
    marginTop: 20,
  },
  previewText: {
    fontSize: 14,
    color: '#3498db',
    marginBottom: 8,
    fontWeight: '600',
  },
  previewMessage: {
    fontSize: 16,
    color: '#fff',
    lineHeight: 22,
  },
});

Różne typy klawiatury

import { SafeAreaView, View, Text, TextInput, StyleSheet, ScrollView } from 'react-native';
import { useState } from 'react';

export default function KeyboardTypesExample() {
  const [email, setEmail] = useState('');
  const [phone, setPhone] = useState('');
  const [amount, setAmount] = useState('');
  const [password, setPassword] = useState('');
  const [url, setUrl] = useState('');

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView contentContainerStyle={styles.scrollContent}>
        <Text style={styles.title}>Typy klawiatury</Text>

        {/* Email */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>Email</Text>
          <TextInput
            style={styles.input}
            value={email}
            onChangeText={setEmail}
            placeholder="email@atlantyda.com"
            placeholderTextColor="#7f8c8d"
            keyboardType="email-address"
            autoCapitalize="none"
            autoCorrect={false}
          />
        </View>

        {/* Telefon */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>Telefon</Text>
          <TextInput
            style={styles.input}
            value={phone}
            onChangeText={setPhone}
            placeholder="+48 123 456 789"
            placeholderTextColor="#7f8c8d"
            keyboardType="phone-pad"
          />
        </View>

        {/* Liczba/kwota */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>Kwota (złoto)</Text>
          <TextInput
            style={styles.input}
            value={amount}
            onChangeText={setAmount}
            placeholder="0.00"
            placeholderTextColor="#7f8c8d"
            keyboardType="decimal-pad"
          />
        </View>

        {/* Hasło */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>Hasło</Text>
          <TextInput
            style={styles.input}
            value={password}
            onChangeText={setPassword}
            placeholder="••••••••"
            placeholderTextColor="#7f8c8d"
            secureTextEntry={true}
            autoCapitalize="none"
          />
        </View>

        {/* URL */}
        <View style={styles.inputGroup}>
          <Text style={styles.label}>Adres URL</Text>
          <TextInput
            style={styles.input}
            value={url}
            onChangeText={setUrl}
            placeholder="https://atlantyda.com"
            placeholderTextColor="#7f8c8d"
            keyboardType="url"
            autoCapitalize="none"
            autoCorrect={false}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  scrollContent: {
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 24,
    textAlign: 'center',
  },
  inputGroup: {
    marginBottom: 16,
  },
  label: {
    fontSize: 14,
    color: '#aed6f1',
    marginBottom: 8,
    fontWeight: '500',
  },
  input: {
    backgroundColor: '#2c3e50',
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: '#fff',
    borderWidth: 1,
    borderColor: '#34495e',
  },
});

Obsługa klawiatury

import {
  SafeAreaView,
  View,
  Text,
  TextInput,
  StyleSheet,
  KeyboardAvoidingView,
  Platform,
  Pressable,
  Keyboard
} from 'react-native';
import { useState } from 'react';

export default function KeyboardHandlingExample() {
  const [message, setMessage] = useState('');

  return (
    <SafeAreaView style={styles.container}>
      {/* KeyboardAvoidingView przesuwa zawartość gdy pojawia się klawiatura */}
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        style={styles.keyboardView}
      >
        {/* Dotknięcie poza inputem ukrywa klawiaturę */}
        <Pressable style={styles.inner} onPress={Keyboard.dismiss}>
          <Text style={styles.title}>Wiadomość w butelce</Text>

          <View style={styles.inputContainer}>
            <TextInput
              style={styles.input}
              value={message}
              onChangeText={setMessage}
              placeholder="Napisz wiadomość..."
              placeholderTextColor="#7f8c8d"
              multiline
              returnKeyType="send"
              onSubmitEditing={() => {
                console.log('Wysłano:', message);
                setMessage('');
                Keyboard.dismiss();
              }}
            />

            <Pressable
              style={styles.sendButton}
              onPress={() => {
                console.log('Wysłano:', message);
                setMessage('');
                Keyboard.dismiss();
              }}
            >
              <Text style={styles.sendButtonText}>Wyślij</Text>
            </Pressable>
          </View>
        </Pressable>
      </KeyboardAvoidingView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  keyboardView: {
    flex: 1,
  },
  inner: {
    flex: 1,
    justifyContent: 'flex-end',
    padding: 20,
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
    marginBottom: 20,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'flex-end',
    gap: 10,
    marginBottom: 20,
  },
  input: {
    flex: 1,
    backgroundColor: '#2c3e50',
    borderRadius: 20,
    paddingHorizontal: 16,
    paddingVertical: 12,
    fontSize: 16,
    color: '#fff',
    maxHeight: 100,
  },
  sendButton: {
    width: 48,
    height: 48,
    borderRadius: 24,
    backgroundColor: '#3498db',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sendButtonText: {
    fontSize: 20,
  },
});

Podsumowanie typów klawiatury

keyboardTypeOpisUżycie
defaultStandardowaTekst ogólny
email-addressZ @ i .Email
numericTylko cyfryLiczby całkowite
decimal-padCyfry z przecinkiemKwoty, liczby dziesiętne
phone-padNumer telefonuTelefon
number-padKlawiatura numerycznaPIN, kody
urlZ / i .comAdresy URL
Kod do tej lekcji: App.tsx
import React, { useState } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export default function App() {
  const [name, setName] = useState('');

  return (
    <View style={styles.container}>
      {/* TODO: dodaj <TextInput>, który:
          - ma value={name}
          - aktualizuje stan przez onChangeText={setName}
          - ma placeholder="Wpisz imię..."
          - korzysta ze stylu styles.input */}

      <Text style={styles.label}>Witaj, {name || 'mieszkańcu Atlantydy'}!</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    backgroundColor: '#1a5276',
  },
  input: {
    backgroundColor: '#2c3e50',
    borderRadius: 8,
    padding: 14,
    fontSize: 16,
    color: '#fff',
    marginBottom: 16,
  },
  label: {
    fontSize: 18,
    color: '#aed6f1',
  },
});

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Sprawdź się

Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.

  1. 1. Jaki keyboardType użyjesz dla pola email?

  2. 2. Jaki prop ukrywa wpisywany tekst (dla hasła)?

  3. 3. Do czego służy KeyboardAvoidingView?

Zadania praktyczne w grze

  • Edytor kodu

    Uzupełnij komponent TextInput

  1. PytanieQuiz: Typ klawiatury dla emaila
  2. PytanieQuiz: Ukrywanie hasła
  3. PytanieQuiz: KeyboardAvoidingView
  4. Zadanie z kodemUzupełnij: TextInput

Przydatne artykuły