React Native 的使用

# React Native 的使用

## 安装环境

### 1.安装Homebrew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

出了错误参见http://www.jianshu.com/p/4e80b42823d5

### 2.安装Node.js

brew install node

注意不要安装 Node.js 的一个叫 n 的工具,没有看错,就是这个工具,别看着别的攻略安装上了他,这玩意简直噩梦。

### 3.安装react-native-cli

npm install -g react-native-cli

若出现错误(可能由于权限不足),则用以下语句进行安装:

sudo npm install -g react-native-cli

如果需要换镜像

npm config set registry https://registry.npm.taobao.org --global

npm config set disturl https://npm.taobao.org/dist --global

### 4.选择安装Watchman Flow

有助于开发,但是不安装也没问题,都是Facebook 提供的工具

brew install watchman

brew install flow

### 5.开发工具

VSCode

https://www.visualstudio.com/en-us/products/code-vs.aspx

### 6.创建项目

#### 6.1 单独的项目

创建一个跨平台的单独项目

react-native init MyRN

稍等片刻 运行完毕后启动他

cd MyRN

react-native run-ios

然后模拟器久启动了

####6.2 在工程中加载RN

新建一个项目

项目根目录下创建文件夹ReactComponent,

ReactComponent文件夹里面创建文件index.ios.js

内容写把刚才创建的MyRN 目录下面的 index.ios.js 文件内容考进去 ,记得最下面名字和工程名字相同

ReactComponent 文件夹里面创建文件package.json

内容:

{

"name": "MyRN",

"version": "0.0.1",

"private": true,

"scripts": {

"start": "node node_modules/react-native/local-cli/cli.js start",

"test": "jest"

},

"dependencies": {

"react": "16.0.0-alpha.6",

"react-native": "0.44.3"

},

"devDependencies": {

"babel-jest": "20.0.1",

"babel-preset-react-native": "1.9.2",

"jest": "20.0.1",

"react-test-renderer": "16.0.0-alpha.6"

},

"jest": {

"preset": "react-native"

}

}

当然也可以从刚才创建的项目拷贝 但是

"react": "16.0.0-alpha.6",

"react-native": "0.44.3"

如果更改的话可能出问题,尽量不要改

然后cd 到ReactComponent

执行

npm install

执行完毕 在 项目根目录创建文件Podfile

内容

source 'https://github.com/CocoaPods/Specs.git'

platform :ios, '8.0'

use_frameworks!

target 'MyRN' do

pod 'Yoga', :path => './ReactComponent/node_modules/react-native/ReactCommon/yoga'

pod 'React', :path => './ReactComponent/node_modules/react-native', :subspecs => [

'Core',

'ART',

'RCTActionSheet',

'RCTAdSupport',

'RCTGeolocation',

'RCTImage',

'RCTNetwork',

'RCTPushNotification',

'RCTSettings',

'RCTText',

'RCTVibration',

'RCTWebSocket',

'RCTLinkingIOS',

]

end

然后在项目根目录执行

pod install

如果pod 出错请自行pod 的出错原因

cd 到 ReactComponent

执行

react-native start

接着 打开xcode 在 ViewController.swift 的 viewDidLoad 方法写上

let str = "http://localhost:8081/index.ios.bundle?platform=ios&dev=true"

let jsCodeLocation = URL(string: str)

let rootView = RCTRootView(bundleURL: jsCodeLocation, moduleName: "MyRN", initialProperties: [:], launchOptions: [:])

self.view = rootView

就可以运行了

这是我根据网上很多资料一步步尝试的,尝试过程中问题有很多,稍后再记录。

特别注意的是 别用最新版本 !!!

你可能感兴趣的:(React Native 的使用)