Создание интерактивного приложения-счётчика
Объедините props и состояние, чтобы создать компонент-счётчик с кнопками увеличения, уменьшения и сброса, которые реактивно обновляют интерфейс.
«Создание интерактивного приложения-счётчика» — бесплатный урок React Native Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения React Native Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс React Native Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Counter App Project Plan
This lesson builds a complete interactive counter app that applies all concepts learned in this course: props for passing data, useState for managing the count, lifted state for sharing between sibling components, and StyleSheet for visual polish. The app will have a display component that shows the current count, three control buttons (Increment, Decrement, Reset), a history log of recent changes, and a step-size selector to change how much each button increments. Planning the component structure before coding prevents confusion.
// Component tree for the Counter App:
// App
// ├── CountDisplay ← shows current count (receives count prop)
// ├── CountControls ← increment/decrement/reset buttons
// │ └── ControlButton ← reusable button component
// ├── StepSelector ← choose step size (1, 5, 10)
// └── HistoryLog ← list of recent operationsSetting Up App State
The App (or screen) component owns all the state: the current count, the step size, and the history log. Because CountDisplay, CountControls, and HistoryLog are siblings that all need different aspects of this state, lifting it to the parent is correct. The history is an array of strings (operation descriptions) that grows with each action. Using a single parent to own all state keeps the logic centralized and easy to follow.
import { useState } from 'react';
export default function CounterApp() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const [history, setHistory] = useState([]);
function addHistory(message) {
setHistory(prev => [message, ...prev].slice(0, 10)); // keep last 10
}
function increment() {
setCount(prev => prev + step);
addHistory(`+${step} → ${count + step}`);
}
function decrement() {
setCount(prev => prev - step);
addHistory(`-${step} → ${count - step}`);
}
function reset() {
setCount(0);
addHistory('Reset → 0');
}
return null; // UI rendered below
}CountDisplay Component
The CountDisplay component is a pure presentational component: it receives the count as a prop and displays it with a dynamic color. Positive counts are green, negative are red, and zero is gray. This is a great example of derived presentation logic — the component doesn't manage state, it just transforms its input prop into visual output. The large number display uses a dramatic font size to make the counter the visual center of attention.
import { View, Text, StyleSheet } from 'react-native';
export default function CountDisplay({ count }) {
const color = count > 0 ? '#2ecc71' : count < 0 ? '#e74c3c' : '#95a5a6';
return (
<View style={styles.container}>
<Text style={styles.label}>Current Count</Text>
<Text style={[styles.count, { color }]}>{count}</Text>
<View style={[styles.bar, { backgroundColor: color }]} />
</View>
);
}
const styles = StyleSheet.create({
container: { alignItems: 'center', paddingVertical: 32 },
label: { fontSize: 14, color: '#999', letterSpacing: 1, textTransform: 'uppercase' },
count: { fontSize: 96, fontWeight: '800', marginVertical: 8 },
bar: { width: 60, height: 4, borderRadius: 2 },
});Reusable ControlButton Component
Build a reusable ControlButton component that accepts a label, an icon, an onPress callback, and a variant ('primary', 'danger', or 'ghost'). The variant determines the button's color scheme. Using a single button component for increment, decrement, and reset avoids duplicating button style code. Each variant maps to a different color set, and the button applies the correct styles automatically based on the prop value.
import { TouchableOpacity, Text, StyleSheet } from 'react-native';
const VARIANT_COLORS = {
primary: { bg: '#4f86f7', text: '#fff', border: '#4f86f7' },
danger: { bg: '#e74c3c', text: '#fff', border: '#e74c3c' },
ghost: { bg: 'transparent', text: '#666', border: '#ddd' },
};
export default function ControlButton({ label, onPress, variant = 'ghost' }) {
const colors = VARIANT_COLORS[variant];
return (
<TouchableOpacity
style={[styles.btn, { backgroundColor: colors.bg, borderColor: colors.border }]}
onPress={onPress}
activeOpacity={0.75}
>
<Text style={[styles.label, { color: colors.text }]}>{label}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
btn: { flex: 1, paddingVertical: 14, borderRadius: 12, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
label: { fontSize: 16, fontWeight: '700' },
});CountControls Layout
The CountControls component renders the three control buttons in a horizontal row. It receives onIncrement, onDecrement, and onReset callback props from the parent. The decrement button uses the 'ghost' variant, increment uses 'primary', and reset uses 'danger'. A flexDirection: 'row' with gap: 10 lays out the three buttons side by side, each taking equal width via flex: 1.
import { View, StyleSheet } from 'react-native';
import ControlButton from './ControlButton';
export default function CountControls({ onIncrement, onDecrement, onReset, step }) {
return (
<View style={styles.row}>
<ControlButton label={`-${step}`} onPress={onDecrement} variant='ghost' />
<ControlButton label='Reset' onPress={onReset} variant='danger' />
<ControlButton label={`+${step}`} onPress={onIncrement} variant='primary' />
</View>
);
}
const styles = StyleSheet.create({
row: {
flexDirection: 'row',
gap: 10,
paddingHorizontal: 20,
marginBottom: 24,
},
});StepSelector Component
The StepSelector lets users choose how much each button adds or subtracts. It renders a row of step option buttons (1, 5, 10, 25). The currently selected step is visually highlighted. When the user taps a step, it calls the onStepChange callback prop, which updates the step state in the parent App. The parent then passes the new step to CountControls so the button labels update accordingly. This is lifted state in action: the selection lives in the parent, shared between the selector and the controls.
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
const STEPS = [1, 5, 10, 25];
export default function StepSelector({ step, onStepChange }) {
return (
<View style={styles.container}>
<Text style={styles.label}>Step Size</Text>
<View style={styles.row}>
{STEPS.map(s => (
<TouchableOpacity
key={s}
style={[styles.option, s === step && styles.selected]}
onPress={() => onStepChange(s)}
>
<Text style={[styles.optionText, s === step && styles.selectedText]}>
{s}
</Text>
</TouchableOpacity>
))}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: { alignItems: 'center', marginBottom: 24 },
label: { fontSize: 13, color: '#999', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 1 },
row: { flexDirection: 'row', gap: 10 },
option: { width: 52, height: 44, borderRadius: 10, borderWidth: 1.5, borderColor: '#ddd', alignItems: 'center', justifyContent: 'center' },
selected: { borderColor: '#4f86f7', backgroundColor: '#4f86f7' },
optionText: { fontSize: 16, fontWeight: '600', color: '#666' },
selectedText: { color: '#fff' },
});HistoryLog Component
The HistoryLog component displays the last 10 operations in a scrollable list. It receives the history array as a prop. Each entry shows an operation description (e.g., '+5 → 15') with a color-coded indicator — green for increments, red for decrements, and orange for resets. Using FlatList handles smooth scrolling if the history fills up. A header shows 'Recent Operations' and a count badge indicates how many operations are recorded.
import { View, Text, FlatList, StyleSheet } from 'react-native';
function EntryColor(text) {
if (text.startsWith('+')) return '#2ecc71';
if (text.startsWith('-')) return '#e74c3c';
return '#f39c12';
}
export default function HistoryLog({ history }) {
if (history.length === 0) return null;
return (
<View style={styles.container}>
<Text style={styles.header}>Recent Operations ({history.length})</Text>
<FlatList
data={history}
keyExtractor={(_, i) => i.toString()}
renderItem={({ item }) => (
<View style={styles.entry}>
<View style={[styles.dot, { backgroundColor: EntryColor(item) }]} />
<Text style={styles.text}>{item}</Text>
</View>
)}
scrollEnabled={false}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { marginHorizontal: 20, padding: 16, backgroundColor: '#f8f9fa', borderRadius: 16 },
header: { fontSize: 13, color: '#999', fontWeight: '600', marginBottom: 10, textTransform: 'uppercase', letterSpacing: 0.5 },
entry: { flexDirection: 'row', alignItems: 'center', paddingVertical: 6, gap: 10 },
dot: { width: 8, height: 8, borderRadius: 4 },
text: { fontSize: 14, color: '#444' },
});Assembling the Full Counter App
Combine all components in the App with the lifted state. The parent holds count, step, and history. It defines the increment, decrement, and reset handler functions that update all three pieces of state atomically. These handlers are passed as callback props to CountControls. The step is passed to both StepSelector (for display) and CountControls (for button labels). The history array is passed to HistoryLog. The entire app's behavior is coordinated from this single parent component.
import { useState } from 'react';
import { SafeAreaView, ScrollView, StyleSheet } from 'react-native';
import CountDisplay from './CountDisplay';
import CountControls from './CountControls';
import StepSelector from './StepSelector';
import HistoryLog from './HistoryLog';
export default function CounterApp() {
const [count, setCount] = useState(0);
const [step, setStep] = useState(1);
const [history, setHistory] = useState([]);
function addHistory(msg) {
setHistory(prev => [msg, ...prev].slice(0, 10));
}
function increment() { setCount(p => { const n = p + step; addHistory('+'+step+' → '+n); return n; }); }
function decrement() { setCount(p => { const n = p - step; addHistory('-'+step+' → '+n); return n; }); }
function reset() { setCount(0); addHistory('Reset → 0'); }
return (
<SafeAreaView style={styles.safe}>
<ScrollView contentContainerStyle={styles.content}>
<CountDisplay count={count} />
<StepSelector step={step} onStepChange={setStep} />
<CountControls
step={step}
onIncrement={increment}
onDecrement={decrement}
onReset={reset}
/>
<HistoryLog history={history} />
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safe: { flex: 1, backgroundColor: '#fff' },
content: { paddingBottom: 32 },
});Adding Haptic Feedback
Polish the counter app with haptic feedback using the expo-haptics module. Light haptic on increment, warning haptic on decrement, and a strong notification on reset. Haptic feedback makes the buttons feel more physical and satisfying, significantly improving the tactile experience on real devices. Call the haptic function inside each handler, right before updating state. Haptic feedback is silent when called on simulators — test on a real device to feel the difference.
import * as Haptics from 'expo-haptics';
// Install: npx expo install expo-haptics
function increment() {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
setCount(prev => {
const next = prev + step;
addHistory('+' + step + ' → ' + next);
return next;
});
}
function decrement() {
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
setCount(prev => {
const next = prev - step;
addHistory('-' + step + ' → ' + next);
return next;
});
}
function reset() {
Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning);
setCount(0);
addHistory('Reset → 0');
}Keyboard Accessibility and usability
Add final accessibility touches to the counter app. Use accessibilityLabel on each button so screen readers announce meaningful descriptions. Use accessibilityState={{ selected: s === step }} on the step selector options to communicate the selected state to assistive technology. Add a accessibilityLiveRegion='polite' to the count display so screen readers announce the new count whenever it changes. These small additions make your app usable by the millions of people who rely on accessibility features on their phones.
// Accessibility additions
// CountDisplay:
<Text
accessibilityLiveRegion='polite'
accessibilityLabel={'Current count: ' + count}
style={[styles.count, { color }]}
>
{count}
</Text>
// ControlButton:
<TouchableOpacity
accessibilityRole='button'
accessibilityLabel={'Increment by ' + step}
onPress={onPress}
style={...}
>
// StepSelector option:
<TouchableOpacity
accessibilityRole='radio'
accessibilityState={{ selected: s === step }}
accessibilityLabel={'Step size ' + s}
onPress={() => onStepChange(s)}
>Persisting the Counter to AsyncStorage
Enhance the counter app by saving the count to AsyncStorage so it survives app restarts. Use useEffect to watch the count value and write it to AsyncStorage whenever it changes. On the first render, read the saved value from AsyncStorage and initialize the count state. This is a minimal but complete example of local data persistence — the same pattern scales to saving user preferences, form drafts, and app configuration. AsyncStorage writes are asynchronous and should not block UI updates.
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useState, useEffect } from 'react';
// npx expo install @react-native-async-storage/async-storage
const COUNT_KEY = '@counter_value';
export default function PersistentCounter() {
const [count, setCount] = useState(0);
const [loaded, setLoaded] = useState(false);
// Load saved count on mount
useEffect(() => {
AsyncStorage.getItem(COUNT_KEY)
.then(stored => {
if (stored !== null) setCount(parseInt(stored, 10));
})
.finally(() => setLoaded(true));
}, []);
// Save count whenever it changes (after initial load)
useEffect(() => {
if (!loaded) return;
AsyncStorage.setItem(COUNT_KEY, count.toString());
}, [count, loaded]);
if (!loaded) return null; // wait for saved value before rendering
return (
<>{/* CountDisplay, CountControls, etc. */}</>
);
}Quick Check
Test your understanding of React Native Mobile Development concepts from this lesson.
Lesson Recap
In this lesson you learned: component decomposition breaks a complex screen into focused, reusable pieces, lifted state in the parent component coordinates behavior across sibling components, and callback props + haptic feedback make the counter interactive and tactile. Next up we explore handling user input with TextInput, touch events, and form components.
Часто задаваемые вопросы
Урок «Создание интерактивного приложения-счётчика» бесплатный?
Да — полный текст урока «Создание интерактивного приложения-счётчика» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс React Native Academy, подпишись на CoddyKit PRO. Курс React Native Academy содержит 4 уроков всего.
Чему я научусь в уроке «Создание интерактивного приложения-счётчика»?
Объедините props и состояние, чтобы создать компонент-счётчик с кнопками увеличения, уменьшения и сброса, которые реактивно обновляют интерфейс. Ты практикуешь React Native Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать React Native Academy?
Предыдущий опыт не требуется. React Native Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Создание интерактивного приложения-счётчика»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке React Native Academy?
Да. Каждый урок React Native Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Передача данных через props
- Управление состоянием компонента с помощью useState
- Подъём состояния
- Создание интерактивного приложения-счётчика