iOS->RN实战分享之基础篇:在现有项目中使用RN

首先:这是一篇实战分享,但这里的内容主要来自于http://facebook.github.io/react-native/releases/0.34/docs/integration-with-existing-apps.html,加上自己的理解。你可以认为这是一篇二手教程,但我个人觉得还是可以给大家带来一些收获。


一个纯RN项目我们可以分为两类(自己新建的项目和下载到的别人的项目):

自己新建的项目:

基本上根据指南的操作就可以,装好node, 通过npm装好命令行工具,再通过命令行创建项目,最后运行之。

Dependencies for Mac + iOS

You will need Xcode, node.js, the React Native command line tools, and Watchman.

We recommend installing node and watchman via Homebrew.

brew install nodebrew install watchman

Node comes with npm, which lets you install the React Native command line interface.

npm install -g react -native -cli

If you get a permission error, try with sudo: sudo npm install -g react-native-cli.

If you get error Cannot find module 'npmlog', try this before: curl -0 -L http://npmjs.org/install.sh | sudo sh.

The easiest way to install Xcode is via the Mac App Store.

Testing your React Native Installation

Use the React Native command line tools to generate a new React Native project called "AwesomeProject", then run react-native run-ios inside the newly created folder.

react -native init AwesomeProject
cd AwesomeProject
react -native run -ios

You should see your new app running in the iOS Simulator shortly. react-native run-ios is just one way to run your app - you can also run it directly from within Xcode or Nuclide.

Modifying your app

Now that you have successfully run the app, let's modify it.

  • Open index.ios.js in your text editor of choice and edit some lines.
  • Hit Command⌘ + R in your iOS Simulator to reload the app and see your change!

下载到的别人的项目:

要让下载到的项目跑起来,我们需要在package.json所在的目录执行npm install安装相应的依赖,然后npm start, 然后执行react-native run-ios(直接通过xcode打开工程运行也是可以的),就可以通过命令行让工程跑起来。


PS:npm的源下载非常缓慢,即使挂了vpn执行 npm install也会消耗半个小时左右的时间(实测),这个时间成本几乎是不可接受的。

我们可以切换到这个源再执行相关命令:npm --registry https://registry.npm.taobao.org info underscore  (切换到taobao源)

当我们需要修改依赖的react native 和  react版本号时,可以修改package.json文件。

使用npm安装rn插件时记得加上save命令,这样会把相关信息自动记录到package.json文件中,后续可以从此文件自动生成相关的插件文件。

npm install --save

集成到现有的项目(iOS):

RN的集成方式是作为一个view加载到iOS的页面里边;而它的依赖(一些在iOS实现的原生组件,rn的精髓)安装我们需要通过cocoapods或是手动的方式集成到工程里。

我们这里的介绍以cocoapods为例,使用cocoapods来集成要方便许多,不需要手动添加lib和修改工程文件里的编译命令等,这些工作由cocoapods帮你完成。

具体而言,我们需要以下几个步骤:

1.无论如何,我们需要通过npm安装相应的依赖,也就是说需要node_modules里面的那一大堆东西。选定一个目录,放置package.json,并执行npm install。

2.在工程下新建pod文件,编辑之:

pod文件示例:

target 'NumberTileGame' do
pod 'React', :path => '../node_modules/react-native', :subspecs => [
'Core',
'RCTImage',
'RCTText',
'RCTWebSocket',
# Add any other subspecs you want to use in your project
]
end

这里的subspecs是你所要用到的所有模块;path表示这里的组件是通过本地路径加载的,那么我们就需要确保pod文件所在路径和node_modules文件夹路径的关系。

这里的../表明 node_modules文件夹在pod文件的上一层。

编辑完成后,建议运行此命令:pod install --verbose --no-repo-update (否则你可能又遭遇漫长的等待,和npm类似,这里还是有国外服务器访问慢的问题,可以切换国内的源),该命令不会执行更新,而安装的组件又来自本地,所以执行过程会比较快。

3. pod安装完成后,从xcode运行项目;执行 npm start(把npm服务跑起来)。

4. 编辑js代码和iOS原生代码,加载RN view。

iOS代码示例:

#import "RCTRootView.h"
- (IBAction)highScoreButtonPressed:(id)sender {
    NSLog(@"High Score Button Pressed");
    //NSURL *jsCodeLocation = [NSURL
                            // URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];
    //192.168.1.102
    NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
    
    RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                 moduleName: @"myRN"
                                                 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];
}

这里的模块名 myRN需要和appRegistry里面注册的名称一致。

js代码示例:

'use strict';

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


class RNHighScores extends React.Component {
  render() {
    console.log(this.props["scores"]);
    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,
  },
});

// Module name
AppRegistry.registerComponent('myRN', () => RNHighScores);

5. 再次运行项目,看效果,可以进行js的编辑和调试工作了。


总结:这里是两大包管理器npm和cocoapods的强强联合,先通过npm从远端拉取相关依赖,再通过cocoapods从本地路径中将所需要的组件加到iOS工程中,做到按需加载。这里需要注意的就是npm运行的路径以及pod文件编写中的本地路径问题。


注意: pod里面的 build active architecture Only 设置需要和原工程保持一致,否则可能会编译不通过且查不到真实的原因,请务必注意。







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值