美文网首页ReactNative
React Native(iOS)进阶一 嵌入到现有原生应用

React Native(iOS)进阶一 嵌入到现有原生应用

作者: 神魔狼 | 来源:发表于2017-03-20 16:00 被阅读60次

这里使用官方推荐的cocoapods进行集成,直接上干货,4步搞定~

1.为了更加符合RN的习惯,我们将原有工程的根目录文件夹名改为ios。
如图所示结构:


屏幕快照 2017-03-20 下午3.34.55.png

2.添加package.json文件,写入

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

这里可以先用终端查看当前reactNative的最新版本

$ npm info react-native

然后在在包含有package.json文件的目录(一般也就是项目根目录)中运行下列命令来安装:

$ npm install

如下所示结构:


屏幕快照 2017-03-20 下午3.42.24.png

3.下一步我们需要在CocoaPods的Podfile中指定我们所需要使用的组件。

在你开始把React Native植入到你的应用中之前,首先要决定具体整合的是React Native框架中的哪些部分。而这就是subspec要做的工作。在创建Podfile文件的时候,需要指定具体安装哪些React Native的依赖库。所指定的每一个库就称为一个subspec。

可用的subspec都列在node_modules/react-native/React.podspec中,基本都是按其功能命名的。一般来说你首先需要添加Core,这一subspec包含了必须的AppRegistry、StyleSheet、View以及其他的一些React Native核心库。如果你想使用React Native的Text库(即<Text>组件),那就需要添加RCTText的subspec。同理,Image需要加入RCTImage,等等。

然后在Podfile文件中写入

platform :ios, ‘8.0’

target ‘FixRN’ do
# 但是如果你的结构不同,那你就要根据实际路径修改下面的`:path`
  pod 'React', :path => '../node_modules/react-native', :subspecs => [
    'Core',
    'RCTText',
    'RCTNetwork',
    'RCTWebSocket',
  ]
# 如果你的RN版本 >= 0.42.0,请加入下面这行
  pod "Yoga", :path => "../node_modules/react-native/ReactCommon/yoga"

end

创建好了Podfile后,就可以开始安装React Native的pod包了。

$ pod install

4.到这里就算集成好了,可以来测试一下

首先创建一个空的index.ios.js文件。一般来说我们把它放置在项目根目录下。

'use strict';

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

export default 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);

在项目的info.plist中加入

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

然后在x-code项目中新建一个RNFirstViewController,这个RNFirstViewController就是一个RN界面,你可以在原生应用任意位置加入它。

#import "RNFirstViewController.h"
#import "RCTRootView.h"

@interface RNFirstViewController ()

@end

@implementation RNFirstViewController

- (void)loadView {
    NSURL *jsCodeLocation = [NSURL
                             URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
    RCTRootView *rootView =
    [[RCTRootView alloc] initWithBundleURL : jsCodeLocation
                         moduleName        : @"RNHighScores"
                         initialProperties :
     @{
       @"scores" : @[
               @{
                   @"name" : @"Alex",
                   @"value": @"42"
                   },
               @{
                   @"name" : @"Joel",
                   @"value": @"30"
                   },
               @{
                   @"name" : @"Tom",
                   @"value": @"10"
                   }
               ]
       }
                          launchOptions    : nil];
    
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"RN First One";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

最后先在根目录下运行

$ npm start

然后在运行项目。

Untitled12123.gif

参考自:http://reactnative.cn/docs/0.42/debugging.html#content

相关文章

网友评论

    本文标题:React Native(iOS)进阶一 嵌入到现有原生应用

    本文链接:https://www.haomeiwen.com/subject/stfinttx.html