iOS開發嵌套ReactNative頁面

來源:互聯網
上載者:User

標籤:版本   des   mon   sources   相關   justify   little   boa   sub   

最近使用ReactNative做項目,有信心今天目標把ReactNative架構掌握,所以自己從每個知識點學習提高自己吧......

步驟如下:

一.建立依賴包檔案(package.json):

React Native的植入過程同時需要React和React Native兩個node依賴包。我們把具體的依賴包記錄在package.json檔案中。

  • 如果項目根目錄中沒有這個檔案,那就自己建立一個。
  • 如果為了目錄結構的美觀,也可以在根目錄下建立一個檔案夾<這裡我沒有使用分檔案夾,我懶得....當然分檔案夾比較好的啦!!>,放置相關的ReactNative檔案.

如果自己建立package.json檔案,終端操作:

cd 需要放置的目錄下(項目的根目錄/項目中自己建立的檔案夾)touch package.json

package.json添加以下內容:我這裡使用的是0.44

{  "name": "iOSNestReactNative",  "version": "0.0.1",  "private": true,  "scripts": {    "start": "node node_modules/react-native/local-cli/cli.js start"  },  "dependencies": {    "react": "16.0.0-alpha.6",    "react-native": "0.44.0"  }}
二、安裝依賴包(node_modules):

使用npm(即node包管理器,Node package manager)來安裝React和React Native模組。這些模組會被安裝到項目根目錄下的node_modules/目錄中。

cd 項目的根目錄/項目中自己建立的檔案夾npm install

等待執行完畢。項目中會多出一個node_modules檔案夾。

三、添加React Native架構(Podfile):

在React和React Native模組成功安裝到node_modules目錄之後,你就可以開始建立Podfile以便選擇所需的組件安裝到應用中。

這裡需要使用CocoaPods喲...我相信做iOS的應該都有這個吧...哈哈??

## 在iOS原生代碼所在的目錄中(也就是`.xcodeproj`檔案所在的目錄)執行:$ cd 項目的根目錄$ pod init

修改Profile檔案:

# 最低適配的版本platform :ios, "9.0"use_frameworks!# target的名字一般與你的項目名字相同target ‘iOSNestReactNative‘ do  # ‘node_modules‘目錄一般位於根目錄中  # 但是如果你的結構不同,那你就要根據實際路徑修改下面的`:path`#記得此處的路徑,如果你有建立一個新的檔案夾存放這些檔案,前面要加上你檔案夾的名字:‘../RNComponent/node_modules/react-native‘,如果沒有,直接如下建立即可。  pod ‘React‘, :path => ‘./node_modules/react-native‘, :subspecs => [    ‘Core‘,    ‘RCTText‘,    ‘RCTNetwork‘,    ‘RCTWebSocket‘, # 這個模組是用於調試功能的    # 在這裡繼續添加你所需要的模組  ] # 如果你的RN版本 >= 0.42.0,請加入下面這行# 該版本號碼是package.json中的“dependencies”字典下面的“react-native”後面對應的內容  pod "Yoga", :path => "./node_modules/react-native/ReactCommon/yoga"end

建立好了Podfile後,就可以開始安裝React Native的pod包了。

執行: pod install即可.

四、代碼整合(index.ios.js檔案建立):

現在我們已經準備好了所有依賴,可以開始著手修改原生代碼來把React Native真正植入到應用中了。

首先建立一個空的index.ios.js檔案。一般來說我們把它放置在同上面的package.json的同級目錄下.

$ cd 項目的根目錄/項目中自己建立的檔案夾$ touch index.ios.js

在index.ios.js檔案裡寫頁面代碼就可以了喲!!!

‘use strict‘;import React,{Component} from ‘react‘;import {  AppRegistry,  StyleSheet,  Text,  View} from ‘react-native‘;class RNHighScores extends React.Component {  render() {    // 這裡是使用Xcode那邊傳過來的資料進行構建組件     var content = this.props[‘NameDict‘].map(       name=><Text key = {name.name}>{name.name}:{name.value}{‘\n‘}</Text>     );    return (      <View style={styles.container}>        <Text style={styles.highScoresTitle}>          跳轉過來啦...嘻嘻!        </Text>        <Text style={styles.scores}>              iOS嵌套ReactNative是不是成功了呢??        </Text>        <Text style={styles.scores}>              {content}        </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);
五、iOS項目中進行初始化配置:

先看一下我的Xcode的目錄結構:

1>首先匯入RCTRootView.h標頭檔;

// #import "RCTRootView.h",更新之後,需要匯入下面的標頭檔。// 官網的評論下方也有說明,否則會提示RCTRootView.h檔案不存在。#import <React/RCTRootView.h>

2>viewDidload中加入代碼:

////  NextViewController.m//  iOSNestReactNative////  Created by 思 彭 on 2017/6/16.//  Copyright ? 2017年 思 彭. All rights reserved.//#import "NextViewController.h"// #import "RCTRootView.h",更新之後,需要匯入下面的標頭檔。// 官網的評論下方也有說明,否則會提示RCTRootView.h檔案不存在。#import <React/RCTRootView.h>@interface NextViewController ()@end@implementation NextViewController- (void)viewDidLoad {    [super viewDidLoad];//    self.view.backgroundColor = [UIColor grayColor];//    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];//    view1.backgroundColor = [UIColor redColor];//    [self.view addSubview:view1];        NSURL *jsCodeLocation = [NSURL                             URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios"];    RCTRootView *rootView =    [[RCTRootView alloc] initWithBundleURL : jsCodeLocation                         moduleName        : @"RNHighScores"                         initialProperties :     @{       @"NameDict" : @[               @{                   @"name" : @"思思",                   @"value": @"棒棒噠"                   },               @{                   @"name" : @"思思sisi",                   @"value": @"嘻嘻"                   }               ]       }                          launchOptions    : nil];    self.view = rootView;}- (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
六、啟動程式開發伺服器,運行Packager:
# 進入到node_modules檔案夾所在的路徑$ cd 項目的根目錄/項目中自己建立的檔案夾$ npm start

注意:直接運行項目會報Could not connect to development server錯誤,需要在項目中配置App Transport Security。(相信這個大家都會的啦~(≧▽≦)/~)
在info.plist中添加http

<key>NSAppTransportSecurity</key>    <dict>        <key>NSAllowsArbitraryLoads</key>        <true/>    </dict>
七、在Xcode中運行項目:

運行結果如下:

大功告成...耶耶耶!

Demo地址:https://github.com/PengSiSi/iOSNestReactNativeDemo

 

iOS開發嵌套ReactNative頁面

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.