React Native安装与环境配置 macOS

安装依赖

按照官方的说法,必须安装的依赖有Node、Watchman 和 React Native 命令行工具以及 Xcode。

Node, Watchman

官方推荐使用Homebrew来安装 Node 和 Watchman。在命令行中执行下列命令安装:

安装Homebrew:

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

安装 Node 和 Watchman:

brew install node
brew install watchman

如果你已经安装了 Node,检查node版本号(node -v  ),但不是最新的版本,输入一些命令进行更新,或者直接去进行下载

brew upgrade node

安装完 Node 后建议设置 npm 镜像以加速后面的过程(或使用*工具)。

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

Watchman则是由 Facebook 提供的监视文件系统变更的工具。安装此工具可以提高开发时的性能(packager 可以快速捕捉文件的变化从而实现实时刷新)。

Yarn、React Native 的命令行工具(react-native-cli)

Yarn是 Facebook 提供的替代 npm 的工具,可以加速 node 模块的下载。React Native 的命令行工具用于执行创建、初始化、更新项目、运行打包服务(packager)等任务。但是在这里,并没有去集成Yarn,依然使用的是npm工具。

npm install -g yarn react-native-cli

到这里为止React Native的依赖环境基本已经配置好了。

Xcode

Xcode的命令行工具

React Native 目前需要Xcode 9.4 或更高版本。启动 Xcode,并在Xcode | Preferences | Locations菜单中检查一下是否装有某个版本的Command Line Tools。Xcode 的命令行工具中包含一些必须的工具,比如git等。

React Native安装与环境配置 macOS

 

React Native创建新项目

创建新项目

使用 React Native 命令行工具来创建一个名为"AwesomeProject"的新项目:

cd /Users/zq/Desktop/Test 
react-native init AwesomeProject

编译并运行 React Native 应用

cd AwesomeProject
react-native run-ios

官方说很快就应该能看到 iOS 模拟器自动启动并运行你的项目,其实并不是这样的,第一次运行的时长长的让人崩溃,但是我们依然的坚持等待。

React Native安装与环境配置 macOS

iOS的原生项目集成ReactNative

配置项目目录结构

在我们已经创建好的工程中,创建一个ReactNativeComponent的文件夹,进行备用.如图:

React Native安装与环境配置 macOS

在ReactNativeComponent目录中创建package.json文件,并填入一下内容:

{
  "name": "ReactNative",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  }
}

注意:"name": "ReactNative" ,ReactNative是项目名,需要改成你自己的工程名

打开终端,然后cd ReactNativeComponent的目录路径,如下:

cd /Users/zq/Desktop/ReactNative/ReactNativeComponent 

然后运行下列命令来安装:

npm add react-native

这样默认会安装最新版本的React Native,同时会打印出类似下面的警告信息(你可能需要滚动屏幕才能注意到):

警告“[email protected]”有未满足的同伴依赖“[email protected]”。

React Native安装与环境配置 macOS

这是正常现象,意味着我们还需要安装指定版本的React(箭头指向的位置):

npm add [email protected]

配置CocoaPods的依赖

在终端中cd 工程目录,然后输入pod init创建Podfile文件,然后在Podfile文件中输入需要集成的文件,如下:

 # 'node_modules'目录一般位于根目录中
 # 但是如果你的结构不同,那你就要根据实际路径修改下面的`:path`
 pod 'React', :path => './ReactNativeCompent/node_modules/react-native', :subspecs => [
 'Core',
 'CxxBridge', # 如果RN版本 >= 0.47则加入此行
 'DevSupport', # 如果RN版本 >= 0.43,则需要加入此行才能开启开发者菜单
 'RCTText',
 'RCTNetwork',
 'RCTWebSocket', # 调试功能需要此模块
 'RCTAnimation', # FlatList和原生动画功能需要此模块
 # 在这里继续添加你所需要的其他RN模块
 ]
# # 如果你的RN版本 >= 0.42.0,则加入下面这行
 pod 'yoga', :path => './ReactNativeCompent/node_modules/react-native/ReactCommon/yoga'
#
 # 如果RN版本 >= 0.45则加入下面三个第三方编译依赖
 pod 'DoubleConversion', :podspec => './ReactNativeCompent/node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
 pod 'glog', :podspec => './ReactNativeCompent/node_modules/react-native/third-party-podspecs/glog.podspec'
 pod 'Folly', :podspec => './ReactNativeCompent/node_modules/react-native/third-party-podspecs/Folly.podspec'

⚠️路径一定不要写错,node_modules的路径要和自己项目的目录匹配(ReactNativeCompent要改为自己所创建的文件名)。

如果在你终端中输入pod install命令,爆出一下错误,恭喜你路径写错了,你需要再仔细检查一下你的文件路径了。

React Native安装与环境配置 macOS

pod 集成这一部分比是较耗时的,但是一定要耐心等待,毕竟好事多磨。

代码集成

现在我们已经准备好了所有依赖,可以开始着手修改原生代码来把React Native真正集成到应用中了。

创建一个index.js文件

首先在ReactNativeCompent目录下创建一个空的index.js文件。

添加你自己的React Native代码

index.js中添加你自己的组件。我们这里只是简单的添加一个<Text>组件,用然后一个带有样式的<View>组件把它包起来。

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

class RNHighScores extends React.Component {
  render() {
    var contents = this.props['scores'].map((score) => (
      <Text key={score.name}>
        {score.name}:{score.value}
        {'\n'}
      </Text>
    ));
    return (
      <View style={styles.container}>
        <Text style={styles.highScoresTitle}>2048 High Scores!</Text>
        <Text style={styles.scores}>{contents}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#FFFFFF',
  },
  highScoresTitle: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  scores: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

// 整体js模块的名称
AppRegistry.registerComponent('RNHighScores', () => RNHighScores);

3、JS调用

首先导入RCTRootView的头文件

#import <React/RCTRootView.h>

然后调用JS文件

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"High Score Button Pressed");
    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];
    
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL: jsCodeLocation
                                moduleName: @"RNHighScores"
                         initialProperties:
     @{
       @"scores" : @[
               @{
                   @"name" : @"Alex",
                   @"value": @"42"
                   },
               @{
                   @"name" : @"Joel",
                   @"value": @"10"
                   }
               ]
       }
                             launchOptions: nil];
    UIViewController *vc = [[UIViewController alloc] init];
    vc.view = rootView;
    [self presentViewController:vc animated:YES completion:nil];
}

为了保证能正常连接本地启动的 rn 服务器,需要在 info.plist 文件中添加以下内容

React Native安装与环境配置 macOS

运行

到这里并不是所有工作已经完成,可以放心运行项目了,我们还有最后的工作需要做。

运行之前我们还需要开启服务器,很简单,只需两步:

1、cd /Users/zq/Desktop/ReactNative/ReactNativeComponent 
2、npm start

如果出现一下结果,就代表服务器已经成功打开了。

React Native安装与环境配置 macOS

现在就可以放心的运行项目了。运行结果如下:

React Native安装与环境配置 macOS

参考资料

React Native中文网:https://reactnative.cn/docs/integration-with-existing-apps/