react 如何编写app
React 编写移动应用的方法
使用 React 编写移动应用主要有两种主流方式:React Native 和 Progressive Web Apps (PWA)。以下是具体实现方法:
React Native 开发原生应用
React Native 允许使用 React 语法开发真正的原生移动应用,支持 iOS 和 Android 平台。
安装 React Native 命令行工具:
npm install -g react-native-cli
创建新项目:
npx react-native init MyApp
运行 iOS 应用(需 Xcode):
cd MyApp
npx react-native run-ios
运行 Android 应用(需 Android Studio):
npx react-native run-android
核心组件示例:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const App = () => {
return (
<View style={styles.container}>
<Text>Hello React Native!</Text>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default App;
开发渐进式 Web 应用 (PWA)
使用 React 创建 PWA 可以让应用在移动浏览器中运行并具备类似原生应用的体验。
使用 Create React App 创建 PWA:
npx create-react-app my-pwa --template cra-template-pwa
注册 Service Worker(在 index.js 中):
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
serviceWorkerRegistration.register();
添加 manifest.json 配置应用元数据:
{
"short_name": "MyApp",
"name": "My React PWA",
"icons": [
{
"src": "icon-192.png",
"type": "image/png",
"sizes": "192x192"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
跨平台开发工具
Expo 提供了更简单的 React Native 开发体验:
npm install -g expo-cli
expo init MyApp
cd MyApp
expo start
Capacitor 可以将 React 应用打包为原生应用:
npm install @capacitor/core @capacitor/cli
npx cap init
npx cap add android
npx cap add ios
性能优化技巧
使用 React.memo 避免不必要的重新渲染:
const MyComponent = React.memo(function MyComponent(props) {
/* 只在 props 变化时重新渲染 */
});
虚拟化长列表(React Native):
import { FlatList } from 'react-native';
<FlatList
data={data}
renderItem={({item}) => <Item title={item.title} />}
keyExtractor={item => item.id}
/>
对于 Web 应用,使用 React.lazy 实现代码分割:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
两种方法各有优势:React Native 提供真正的原生体验和性能,PWA 则更易于部署和维护。选择取决于项目需求、目标用户和技术预算。







