一、React Native工程结构分析
1) 初始化RN工程
1 | react-native init LKDemo2 |
2) 工程目录结构图

3)工程启动流程分析
- iOS工程或安卓工程一启动,就会加载目录中
index.js文件,通过AppRegistry去注册组件,并且把注册完成的组件输出给iOS端或Android端:
1 | // 引入注册组件模块 |
- 通过Xcode打开iOS工程,或者Android Studio打开Android工程,此处以iOS端为例子。找到AppDelegate.m文件,查看客户端加载方法:

代理文件中通过该方法加载JS端输出的模块,注意模块的名称两端必须保持一致:
1
initWithBridge:bridge moduleName:@"MyRNDemo" initialProperties:nil
代理文件解析加载注释如下
1 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions |
4)App.js文件运行步骤
- 加载React模块,使用其内部的API,比如:jsx语法;
- 加载React Native原生组件,比如:
SafeAreaView, StyleSheet, View, Text,Image等; - 自定义组件类,作为模块的输出;
- 创建样式对象,传入样式对象,根据样式中的对象描述,创建样式表
- 导出当前模块
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56/**
* 撩课学院
* https://itlike.com
*/
// 1. 加载React模块
import React from 'react';
// 2. 加载原生组件
import {
SafeAreaView,
StyleSheet,
View,
Text,
StatusBar,
Image
} from 'react-native';
// 3. 自定义组件(程序入口组件)
const App: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView style={styles.safeView}>
<View style={styles.viewStyle}>
<Image
style={{width: 168, height: 168}}
source={{uri: 'http://www.itlike.com/template/simple/res/404/img/xiaoliao.png'}}
/>
<Text style={styles.textStyle}>小撩陪你开启RN学习之旅!</Text>
</View>
</SafeAreaView>
</>
);
};
// 4. 创建样式对象
// 传入样式对象,根据样式中的对象描述,创建样式表
const styles = StyleSheet.create({
safeView: {
flex: 1
},
viewStyle: {
display: 'flex',
flex: 1,
justifyContent:'center',
alignItems: 'center'
},
textStyle: {
fontSize: 20
}
});
// 5. 导出当前模块
export default App;
二、React Native语法分析
1)JSX语法
JSX语法是一个比较高级但很直观的JS语法糖。我们在创建View的结构是,可以用类似HTML标签的形式创建,当然最终在编译是还是会转换成JS代码。
- 函数中只要返回组件,都需要用()包裹
1
2
3
4
5const App: () => React$Node = () => {
return (
<View></View>
);
}; - 函数中除字符串以外,赋值时都需要用{}包裹
1
<SafeAreaView style={styles.safeView}> </SafeAreaView>
1
2<Image style={{width: 168, height: 168}} source={{uri: 'http://www.itlike.com/template/simple/res/404/img/xiaoliao.png'}}
/> - 组件内使用变量时,都需要用大括号包裹,否则会被当成普通字符串处理。
1
2const str = '引擎计划';
<Text>{str}</Text>2)样式对象文件
内部以键值对的形式,取值如同JS中的对象调用。1
2
3
4
5
6
7
8const styles = StyleSheet.create({
viewStyle: {
display: 'flex',
flex: 1,
justifyContent:'center',
alignItems: 'center'
}
});