9. ScrollView
ScrollView — прокручиваемый контейнер для небольших списков. Для больших данных используй FlatList.
Когда что использовать
Заголовок раздела «Когда что использовать»| ScrollView | FlatList |
|---|---|
| Небольшое кол-во элементов (< 30) | Большие списки |
| Разнородный контент | Однородные элементы |
| Рендерит ВСЁ сразу | Виртуализация |
| Формы, детали товара | Лента, чат, каталог |
Базовое использование
Заголовок раздела «Базовое использование»import { ScrollView, View, Text } from 'react-native';
<ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 16 }} showsVerticalScrollIndicator={false}> <Text>Контент 1</Text> <Text>Контент 2</Text> {/* ...много элементов */}</ScrollView>Горизонтальный скролл
Заголовок раздела «Горизонтальный скролл»<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} pagingEnabled={true} // Постраничная прокрутка (карусель!) contentContainerStyle={{ gap: 12 }}> {items.map(item => <Card key={item.id} item={item} />)}</ScrollView>RefreshControl (Pull to Refresh)
Заголовок раздела «RefreshControl (Pull to Refresh)»import { ScrollView, RefreshControl } from 'react-native';
const [refreshing, setRefreshing] = useState(false);
<ScrollView refreshControl={ <RefreshControl refreshing={refreshing} onRefresh={async () => { setRefreshing(true); await loadData(); setRefreshing(false); }} tintColor="#cba6f7" // iOS colors={['#cba6f7']} // Android /> }>Keyboard Avoiding (форма с клавиатурой)
Заголовок раздела «Keyboard Avoiding (форма с клавиатурой)»import { KeyboardAvoidingView, ScrollView, Platform } from 'react-native';
<KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : 'height'}> <ScrollView keyboardShouldPersistTaps="handled"> {/* Форма с TextInput */} </ScrollView></KeyboardAvoidingView>onScroll — отслеживание позиции
Заголовок раздела «onScroll — отслеживание позиции»import { Animated } from 'react-native';
const scrollY = useRef(new Animated.Value(0)).current;
<Animated.ScrollView onScroll={Animated.event( [{ nativeEvent: { contentOffset: { y: scrollY } } }], { useNativeDriver: true } )} scrollEventThrottle={16} // 60fps> {/* Parallax header, sticky header etc. */}</Animated.ScrollView>scrollTo — программная прокрутка
Заголовок раздела «scrollTo — программная прокрутка»const scrollRef = useRef(null);
// Прокрутить вверхscrollRef.current?.scrollTo({ y: 0, animated: true });
// Прокрутить к позицииscrollRef.current?.scrollTo({ x: 200, y: 400, animated: true });
// До концаscrollRef.current?.scrollToEnd({ animated: true });
<ScrollView ref={scrollRef}>