Kurs React Native · Moduł 1: Pierwsza aplikacja

ScrollView i SafeAreaView

4 min czytania ·
W tej lekcji4

Gdy zawartość nie mieści się na ekranie, potrzebujemy przewijania. A SafeAreaView chroni przed notchem i zaokrąglonymi rogami!

SafeAreaView - bezpieczne marginesy

Współczesne telefony mają notche, dynamic islands i zaokrąglone rogi. SafeAreaView automatycznie dodaje odpowiednie marginesy:

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

export default function SafeAreaExample() {
  return (
    <SafeAreaView style={styles.safeArea}>
      <View style={styles.content}>
        <Text style={styles.title}>Bezpieczna strefa</Text>
        <Text style={styles.description}>
          Ten tekst nie zostanie przycięty przez notch ani zaokrąglone rogi!
        </Text>
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  safeArea: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  content: {
    flex: 1,
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
  },
  description: {
    fontSize: 16,
    color: '#aed6f1',
    marginTop: 10,
  },
});

Lepsze rozwiązanie: expo-safe-area-context

npx expo install react-native-safe-area-context
import { View, Text, StyleSheet } from 'react-native';
import { SafeAreaProvider, SafeAreaView, useSafeAreaInsets } from 'react-native-safe-area-context';

// Użyj w głównym pliku app/_layout.tsx
function RootLayout() {
  return (
    <SafeAreaProvider>
      <App />
    </SafeAreaProvider>
  );
}

// W komponentach
function MyScreen() {
  const insets = useSafeAreaInsets(); // Dostęp do wartości marginesów

  return (
    <SafeAreaView style={styles.container} edges={['top', 'bottom']}>
      <Text>Top inset: {insets.top}px</Text>
      <Text>Bottom inset: {insets.bottom}px</Text>
    </SafeAreaView>
  );
}

ScrollView - przewijanie zawartości

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

export default function ScrollViewExample() {
  const treasures = [
    { id: 1, name: 'Diament Posejdona', rarity: 'Legendarny' },
    { id: 2, name: 'Trójząb mocy', rarity: 'Epicki' },
    { id: 3, name: 'Muszla mądrości', rarity: 'Rzadki' },
    { id: 4, name: 'Kotwica giganta', rarity: 'Zwykły' },
    { id: 5, name: 'Klucz do bram', rarity: 'Epicki' },
    { id: 6, name: 'Starożytny zwój', rarity: 'Rzadki' },
    { id: 7, name: 'Amfora bogów', rarity: 'Legendarny' },
    { id: 8, name: 'Złota moneta', rarity: 'Zwykły' },
    { id: 9, name: 'Klejnot Krakena', rarity: 'Legendarny' },
    { id: 10, name: 'Esencja oceanu', rarity: 'Epicki' },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>Skarby Atlantydy</Text>

      <ScrollView
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={true}
      >
        {treasures.map((treasure) => (
          <View key={treasure.id} style={styles.card}>
            <Text style={styles.treasureName}>{treasure.name}</Text>
            <Text style={[
              styles.rarity,
              treasure.rarity === 'Legendarny' && styles.legendary,
              treasure.rarity === 'Epicki' && styles.epic,
              treasure.rarity === 'Rzadki' && styles.rare,
            ]}>
              {treasure.rarity}
            </Text>
          </View>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  header: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
    textAlign: 'center',
    paddingVertical: 16,
  },
  scrollView: {
    flex: 1,
  },
  scrollContent: {
    padding: 16,
    gap: 12,
  },
  card: {
    backgroundColor: '#2c3e50',
    borderRadius: 12,
    padding: 16,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  treasureName: {
    fontSize: 16,
    color: '#fff',
    fontWeight: '500',
  },
  rarity: {
    fontSize: 12,
    color: '#95a5a6',
    fontWeight: '600',
    paddingHorizontal: 8,
    paddingVertical: 4,
    borderRadius: 4,
    overflow: 'hidden',
  },
  legendary: {
    backgroundColor: '#f39c12',
    color: '#fff',
  },
  epic: {
    backgroundColor: '#9b59b6',
    color: '#fff',
  },
  rare: {
    backgroundColor: '#3498db',
    color: '#fff',
  },
});

ScrollView - przewijanie poziome

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

export default function HorizontalScrollExample() {
  const locations = [
    { id: 1, name: 'Pałac Posejdona', image: 'https://picsum.photos/200/150?random=1' },
    { id: 2, name: 'Świątynia Głębin', image: 'https://picsum.photos/200/150?random=2' },
    { id: 3, name: 'Grota Krakena', image: 'https://picsum.photos/200/150?random=3' },
    { id: 4, name: 'Ogrody Koralowe', image: 'https://picsum.photos/200/150?random=4' },
    { id: 5, name: 'Wrak Titanica', image: 'https://picsum.photos/200/150?random=5' },
  ];

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>Odkryj lokacje</Text>

      <ScrollView
        horizontal={true}
        showsHorizontalScrollIndicator={false}
        contentContainerStyle={styles.horizontalScroll}
        snapToInterval={220} // Snap do kart
        decelerationRate="fast"
      >
        {locations.map((location) => (
          <View key={location.id} style={styles.locationCard}>
            <Image
              source={{ uri: location.image }}
              style={styles.locationImage}
            />
            <Text style={styles.locationName}>{location.name}</Text>
          </View>
        ))}
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  header: {
    fontSize: 20,
    fontWeight: 'bold',
    color: '#fff',
    padding: 16,
  },
  horizontalScroll: {
    paddingHorizontal: 16,
    gap: 16,
  },
  locationCard: {
    width: 200,
    backgroundColor: '#2c3e50',
    borderRadius: 12,
    overflow: 'hidden',
  },
  locationImage: {
    width: '100%',
    height: 120,
  },
  locationName: {
    fontSize: 14,
    fontWeight: '600',
    color: '#fff',
    padding: 12,
    textAlign: 'center',
  },
});

RefreshControl - pull to refresh

import { SafeAreaView, ScrollView, Text, StyleSheet, RefreshControl } from 'react-native';
import { useState, useCallback } from 'react';

export default function RefreshExample() {
  const [refreshing, setRefreshing] = useState(false);
  const [data, setData] = useState('Ostatnia aktualizacja: nigdy');

  const onRefresh = useCallback(() => {
    setRefreshing(true);

    // Symulacja pobrania danych
    setTimeout(() => {
      setData(`Ostatnia aktualizacja: ${new Date().toLocaleTimeString()}`);
      setRefreshing(false);
    }, 2000);
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        refreshControl={
          <RefreshControl
            refreshing={refreshing}
            onRefresh={onRefresh}
            colors={['#3498db']} // Android
            tintColor="#3498db" // iOS
          />
        }
      >
        <Text style={styles.instruction}>
          Pociągnij w dół, aby odświeżyć
        </Text>
        <Text style={styles.data}>{data}</Text>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a5276',
  },
  scrollContent: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  instruction: {
    fontSize: 16,
    color: '#bdc3c7',
    marginBottom: 20,
  },
  data: {
    fontSize: 18,
    color: '#fff',
    fontWeight: '600',
  },
});

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. Do czego służy SafeAreaView?

  2. 2. Który prop włącza przewijanie poziome w ScrollView?

  3. 3. Jaki komponent używamy do implementacji 'pull to refresh' w ScrollView?

  1. PytanieQuiz: SafeAreaView
  2. PytanieQuiz: ScrollView poziomy
  3. PytanieQuiz: Pull to refresh

Przydatne artykuły