React Native (一) 环境搭建

安装步骤主要参考 官方文档

主要就是安装 node ,再者一些 watchdog 等一类的工具,然后就是 Xcode ,模拟器 安卓的 SDK JDK 一类的。这些工具因为之前做个 Node JS 以及 iOS 和安卓开发都已经安装好了,这里主要记录几个一开始遇到的问题:

问题 1: 无法运行 iOS 模拟器

1
2
3
4
5
6
7
react-native run-ios
Scanning folders for symlinks in /Users/maple/Developer/RN/AwesomeProject/node_modules (12ms)
Found Xcode project AwesomeProject.xcodeproj
xcrun: error: unable to find utility "instruments", not a developer tool or in PATH

Command failed: xcrun instruments -s
xcrun: error: unable to find utility "instruments", not a developer tool or in PATH

解决方案:

1
2
 sudo xcode-select -s /Applications/Xcode.app/Contents/Developer/
Password: 输入密码

重新运行即可

问题二: iOS 模拟器运行报错 ‘No bundle URL present.

针对这个问题是这样解决的,开启两个终端,Terminal1 和 Terminal2:

Terminal1 输入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$react-native start
Scanning folders for symlinks in /Users/maple/Developer/RN/AwesomeProject/node_modules (15ms)
┌──────────────────────────────────────────────────────────────────────────────┐
│ │
│ Running Metro Bundler on port 8081. │
│ │
│ Keep Metro running while developing on any JS projects. Feel free to │
│ close this tab and run your own Metro instance if you prefer. │
│ │
│ https://github.com/facebook/react-native │
│ │
└──────────────────────────────────────────────────────────────────────────────┘

Looking for JS files in
/Users/maple/Developer/RN/AwesomeProject


Metro Bundler ready.

Loading dependency graph, done.

Terminal2 输入:

1
react-native run-ios

这样就可以运行起来了

初步接触 RN 中的 JS

根据官方文档中的说法,在开发的过程中主要面对的就是 App.js 文件,所以大体上看下这个文件内容,分成四部分:

  1. 引入文件包 import
  2. 格式化字符串 instructions ,内部通过 ios: 和 android: 做了显示内容的区分
  3. render() 通过内嵌 XML 文件显示文本
  4. style 文字显示样式的属性设置
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

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';

const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
android:
'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});

type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.instructions}>To get started, edit App.js</Text>
<Text style={styles.instructions}>{instructions}</Text>
</View>
);
}
}

const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
-------------本文结束谢谢欣赏-------------
Alice wechat