iOS在原生项目中插入React Native(最终版)

来源:互联网 发布:苏联黑科技 知乎 编辑:程序博客网 时间:2024/05/18 20:33

如果你在找在原生项目中插入react native的教程,那么这将是你最后查找的教程。O(∩_∩)O

本文的前提是电脑已经安装过React-Native相关环境和cocoapods。
STEP 1 安装node_modules包

创建package.json文件在项目的根目录下,这是为工程添加依赖库。里面有工程的版本信息和所需要的依赖库,第三方库等
例子如下

{  "name": "YourProjectName",  "version": "0.0.1",  "private": true,  "scripts": {    "start": "node node_modules/react-native/local-cli/cli.js start"  },  //所需要的库  "dependencies": {    "react": "15.2.1",    "react-native": "0.31.0",    "react-native-looped-carousel": "0.0.12",    "react-native-swiper": "^1.4.9"  }}

然后在项目的根目录下

npm install

安装package.json中所需要的库。
STEP 2 pod所需要的库到工程
创建podfile文件,利用Cocoapods安装podfile中所涉及到的库。

target 'YourProjectName' do  # Your 'node_modules' directory is probably in the root of your project,  # but if not, adjust the `:path` accordingly  pod 'React', :path => '../node_modules/react-native', :subspecs => [#pod的路径    'Core',    'RCTText',    'RCTWebSocket', # 你需要用到的库  ]end

然后进行 pod install 安装库

pod install

STEP 3 创建index.ios文件
在根目录下创建index.ios文件。为了方便我们直接把代码写到了根目录下。

'use strict';import React from 'react';import {  AppRegistry,  StyleSheet,  Text,  View} from 'react-native';class YourProjectName 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,  },});// Module nameAppRegistry.registerComponent('YourProjectName', () => YourProjectName);

STEP 4添加到原生项目
首先导入头文件

#import "RCTBundleURLProvider.h"#import "RCTRootView.h"

获得RCTRootView

 NSURL *jsCodeLocation = [NSURL                             URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];    RCTRootView *rootView =    [[RCTRootView alloc] initWithBundleURL : jsCodeLocation                         moduleName        : @"YourProjectName"                         initialProperties :     @{       @"scores" : @[               @{                   @"name" : @"Alex",                   @"value": @"42"                   },               @{                   @"name" : @"Joel",                   @"value": @"10"                   }               ]       }                          launchOptions    : nil];    self.view = rootView;

到这里基本就结束了,但是现在运行会提示服务器没有打开,这时候在根目录下npm start 开启服务器,在运行项目或者react-native run-ios。就大功告成了。

0 0
原创粉丝点击