react native 如何
React Native 开发基础
React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Android 应用。
环境搭建
确保 Node.js 版本在 14 以上,安装 React Native 命令行工具:
npm install -g react-native-cli
对于 Android 开发,需要安装 Android Studio 并配置环境变量。对于 iOS 开发,需要 Xcode 和 CocoaPods。
创建新项目
使用以下命令创建新项目:
npx react-native init MyProject
进入项目目录并启动 Metro 打包工具:
cd MyProject
npx react-native start
在另一个终端窗口中运行应用:
npx react-native run-android
# 或
npx react-native run-ios
基本组件使用
React Native 提供了一系列核心组件,例如 View、Text、Image 等。这些组件可以直接在代码中使用:

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;
样式处理
React Native 使用类似 CSS 的样式系统,但不支持所有 CSS 属性。样式通常通过 StyleSheet.create 方法定义:
const styles = StyleSheet.create({
text: {
color: 'red',
fontSize: 16,
fontWeight: 'bold',
},
});
导航处理
对于应用内导航,可以使用 React Navigation 库:
npm install @react-navigation/native @react-navigation/stack
基本导航配置示例:
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Details" component={DetailsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
状态管理
可以使用 React 的 useState 钩子或更复杂的状态管理库如 Redux:

import React, { useState } from 'react';
const Counter = () => {
const [count, setCount] = useState(0);
return (
<View>
<Text>Count: {count}</Text>
<Button title="Increment" onPress={() => setCount(count + 1)} />
</View>
);
};
调试技巧
React Native 提供了多种调试方式:
- 在模拟器中摇动设备调出开发者菜单
- 使用 Chrome 开发者工具调试 JavaScript 代码
- 安装 React Native Debugger 进行更全面的调试
- 使用 Flipper 工具查看应用日志和性能
性能优化
提高 React Native 应用性能的方法:
- 使用
FlatList替代ScrollView渲染长列表 - 避免不必要的重新渲染,使用
React.memo或useMemo - 减少 bridge 通信,批量处理原生调用
- 使用 Hermes JavaScript 引擎提升启动速度
原生模块集成
当需要访问平台特定功能时,可以创建原生模块:
Android (Java):
public class CustomModule extends ReactContextBaseJavaModule {
@ReactMethod
public void showToast(String message) {
Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
iOS (Objective-C):
RCT_EXPORT_METHOD(showAlert:(NSString *)message)
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Alert"
message:message
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:alert animated:YES completion:nil];
}
然后在 JavaScript 中通过 NativeModules 访问这些方法。





