Перейти к содержимому

5. Стилизация (StyleSheet)

В React Native нет CSS — есть StyleSheet API с похожим синтаксисом. Стили описываются как JavaScript объекты.

import { StyleSheet, View, Text } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#1e1e2e',
padding: 16,
},
title: {
fontSize: 24,
fontWeight: 'bold',
color: '#cba6f7',
marginBottom: 8,
},
});
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.title}>Привет!</Text>
</View>
);
}

StyleSheet.create не обязателен (можно передавать объект напрямую), но даёт:

  • Валидацию стилей
  • Лучшую производительность (стили кешируются по ID)
  • Автодополнение в IDE
CSSReact NativeПримечание
background-colorbackgroundColorcamelCase
font-size: 16pxfontSize: 16Числа без единиц
margin: 10px 20pxmarginHorizontal: 20, marginVertical: 10Нет shorthand
border: 1px solid redborderWidth: 1, borderColor: 'red'Разделено
font-weight: 600fontWeight: '600'Строка!
display: flexПо умолчанию flexВсегда flex
flex-direction: rowflexDirection: 'row'По умолчанию ‘column’
// Пиксели (density-independent pixels - dp)
// Автоматически масштабируются по dpi экрана
width: 200 // 200dp
// Проценты (от родительского контейнера)
width: '50%'
// Flex (пропорциональное распределение)
flex: 1
// Из Dimensions API
import { Dimensions } from 'react-native';
const { width, height } = Dimensions.get('window');
width: width * 0.8 // 80% ширины экрана
// Массив стилей (последний побеждает)
<View style={[styles.box, isActive && styles.boxActive]} />
// Динамические стили
<View style={{ backgroundColor: isError ? '#f38ba8' : '#a6e3a1' }} />
// Pressable с состоянием
<Pressable style={({ pressed }) => [
styles.button,
pressed && styles.buttonPressed,
]}>
import { Platform, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
shadow: Platform.select({
ios: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.25,
shadowRadius: 4,
},
android: {
elevation: 4, // Android использует elevation для тени
},
}),
});
// Встроенные системные шрифты
fontFamily: 'System' // San Francisco (iOS) / Roboto (Android)
fontFamily: 'monospace' // Monospace системный
// Кастомные шрифты (через expo-font)
import { useFonts } from 'expo-font';
const [fontsLoaded] = useFonts({
'Inter-Regular': require('./assets/fonts/Inter-Regular.ttf'),
'Inter-Bold': require('./assets/fonts/Inter-Bold.ttf'),
});
// Использование
fontFamily: 'Inter-Bold'
// Карточка с тенью
card: {
backgroundColor: '#313244',
borderRadius: 16,
padding: 16,
...Platform.select({
ios: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 8,
},
android: { elevation: 8 },
}),
},
// Абсолютное позиционирование
badge: {
position: 'absolute',
top: -4,
right: -4,
width: 18,
height: 18,
borderRadius: 9,
backgroundColor: '#f38ba8',
justifyContent: 'center',
alignItems: 'center',
},
// Полноэкранный overlay
overlay: {
...StyleSheet.absoluteFillObject, // top:0, left:0, right:0, bottom:0
backgroundColor: 'rgba(0, 0, 0, 0.5)',
}