0Pricing
React Native Academy · 课时

构建交互式计数器应用

结合 props 和状态构建计数器组件,提供递增、递减和重置按钮,以响应式方式更新界面。

构建交互式计数器应用 是 CoddyKit 上的免费 React Native Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 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 operations

Setting 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.

常见问题解答

「构建交互式计数器应用」课时是免费的吗?

是的 — 「构建交互式计数器应用」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 React Native Academy 课程的其余内容,请升级到 CoddyKit PRO。 React Native Academy 课程共包含 4 节课。

「构建交互式计数器应用」这节课中我会学到什么?

结合 props 和状态构建计数器组件,提供递增、递减和重置按钮,以响应式方式更新界面。 你通过在浏览器中直接运行的动手代码来练习 React Native Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 React Native Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 React Native Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「构建交互式计数器应用」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 React Native Academy 课中编写并运行代码吗?

能。每节 React Native Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 props 传递数据
  2. 使用 useState 管理组件状态
  3. 提升状态
  4. 构建交互式计数器应用
← 返回 React Native Academy