在本文中,我们将创建一个基于 React Native 的简单计数器应用。React Native 是一款闻名且适应性强的工具,用于构建可在各种平台上无缝运行的移动应用程序,它架起了 Web 开发与移动应用开发之间的桥梁。React Native 使开发人员能够构建在 Android 和 iOS 平台上都具有无缝兼容性的强大且高效的应用程序。
- 对于本教程中的 安装 过程,我们将使用 Expo CLI,它在运行 React Native 应用时能提供更佳的体验。
- Expo CLI 是一个利用 JavaScript 和 React 的开发平台。它帮助程序员为 iOS、Android 和 Web 创建移动应用程序。Expo 通过提供各种工具和服务简化了开发流程,并使我们能够构建高质量的应用程序。
前提条件:
- React Native 简介
- React Native 组件
- React useState
- Expo CLI
- Node.js 和 npm (Node Package Manager)
创建 React Native 应用程序的步骤
步骤 1:使用 Expo CLI 创建 React Native 应用程序
使用 Expo CLI,运行以下命令来创建一个新的 React Native 应用程序:
npx create-expo-app SimpleCounterApp
步骤 2: 使用以下命令导航到项目目录:
cd SimpleCounterApp
项目结构:
!React-Native-Project-Structure
实现思路
我们将使用 useState 钩子来管理计数器的值。我们将实现两个函数,handleIncrement 和 handleDecrement,用于更新计数状态。为了增强视觉吸引力,我们将使用 StyleSheet 来设置计数器用户界面的样式。Counter 组件本身将显示当前的计数值,并提供增加和减少计数的按钮。最后,在主 App 组件中,我们将渲染 Counter 组件。
示例:
文件名: App.js
JavaScript
“
import React, { useState } from "react";
import { View, Text,
TextInput, TouchableOpacity,
StyleSheet } from "react-native";
const App = () => {
const [counter, setCounter] = useState(0);
const [initialCount, setInitialCount] = useState(0);
const handleInitialCountChange = (value) => {
setInitialCount(Number(value));
};
const handleReset = () => {
setCounter(initialCount);
};
const handleClick1 = () => {
setCounter(counter + 1);
};
const handleClick2 = () => {
setCounter(counter – 1);
};
return (
极客代码
计数器应用
{counter}
<TouchableOpacity style={styles.button}
onPress={handleClick1}>
Increment
<TouchableOpacity style={styles.button}
onPress={handleClick2}>
Decrement
<TextInput
keyboardType="numeric"
value={initialCount.toString()}
onChangeText={handleInitialCountChange}
style={{ padding: 10,
fontSize: 16,
borderRadius: 8,
borderColor: ‘black‘,
borderWidth: 1 }}
/>
<TouchableOpacity
onPress={handleReset}
style={styles.setInitialCountButton}
>
Set Initial Count
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#f8f8f8",
},
header: {
fontSize: 18,
marginVertical: 10,
color: "#333",
textTransform: "uppercase",
},
heading: {