React Native集成到原生項(xiàng)目iOS

本篇文章將帶領(lǐng)大家把React Native 集成到iOS Native 項(xiàng)目中,實(shí)現(xiàn)OC和React Native的混合開(kāi)發(fā)

一、準(zhǔn)備工作:
搭建React Native 開(kāi)發(fā)環(huán)境,還沒(méi)有搭建好的同學(xué),可以參照React Native 中文網(wǎng)進(jìn)行搭建,里面的文檔已經(jīng)很明了了。
本次我們還需要cocoapods ,ios的三方庫(kù)管理工具,用于把React Native framework 導(dǎo)入到ios Native 項(xiàng)目中
tips:還沒(méi)有安裝cocoapods的百度上有很多安裝的教程,這里不再敘述

二、開(kāi)始集成React Native
1)首先新建一個(gè)ios Obj-c Native 工程,在這里我們?nèi)∶麨镺CToRNTestDemo?

2)我們?cè)诠こ谈夸浵聞?chuàng)建一個(gè)文件夾,用于存放React Native 模塊,這個(gè)文件夾可以自己取名(在這里我們?nèi)∶麨镽NComponent)如圖:

image.png

3)在RNComponent這個(gè)文件夾內(nèi),我們創(chuàng)建一個(gè)package.json的文件,用于初始化React Native 。 注意這個(gè)package.json文件名字是固定的。

4)然后我們?cè)谶@個(gè)package.json文件內(nèi)指定react native 的版本號(hào)等信息,如圖:

image.png

我們需把第一行的name 改為本工程的名字(OCToRNTestDemo)

tips:我們可以先init[react-native init RNTextdemo]一個(gè)RN的項(xiàng)目,然后把這個(gè)項(xiàng)目中的package.json文件給復(fù)制到RNComponent這個(gè)文件夾內(nèi)。

  1. 下面我們用npm install 操作安裝React Native模塊
    打開(kāi)命令終端 cd 到RNComponent文件夾下
    輸入命令: npm install

安裝完成之后,接下來(lái)我們用cocopods關(guān)聯(lián)React Native依賴。

  1. cd 到ios工程根目錄下 ,
    輸入:pod init
    然后:vim podfile
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'OCToRNTestDemo' do
  # Uncomment the next line if you're using Swift or would like to use dynamic frameworks
  # use_frameworks!
pod 'Yoga', :path=> './RNComponent/node_modules/react-native/ReactCommon/yoga'
pod 'React', :path => ‘./RNComponent/node_modules/react-native', :subspecs => [
  'Core',
  'ART',
  'RCTActionSheet',
  'RCTAdSupport',
  'RCTGeolocation',
  'RCTImage',
  'RCTNetwork',
  'RCTPushNotification',
  'RCTSettings',
  'RCTText',
  'RCTVibration',
  'RCTWebSocket',
  'RCTLinkingIOS'
]

  # Pods for OCToRNTestDemo

  target 'OCToRNTestDemoTests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'OCToRNTestDemoUITests' do
    inherit! :search_paths
    # Pods for testing
  end

end

tips:

  1. path 中的RNComponent改為剛剛你自己在工程根目錄下建的文件夾名字
  2. pod 'Yoga' 這行代碼如果不指定yoga,在pod install 時(shí)可能會(huì)報(bào)找不到y(tǒng)oga的錯(cuò)誤
    3.數(shù)組中的pod 'React', :path => ‘./RNComponent/node_modules/react-native', :subspecs => [
    'Core',
    'ART',
    'RCTActionSheet',
    'RCTAdSupport',
    'RCTGeolocation',
    'RCTImage',
    'RCTNetwork',
    'RCTPushNotification',
    'RCTSettings',
    'RCTText',
    'RCTVibration',
    'RCTWebSocket',
    'RCTLinkingIOS'
    ] 視你需要用到的庫(kù),如果不需要?jiǎng)t可以刪除

修改好podfile文件后運(yùn)行:pod install


image.png

這樣便添加好了依賴

7) 在RNComponent 添加index.ios.js 的RN入口文件
文件代碼:

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

class NativeRNApp extends Component {
  render() {
    return (
      <View style={styles.container}>
       <FlatList 
        renderItem={({item})=>{
          return <Text style={{paddingTop:30,fontSize:30}}>{item.key}</Text>
        }}
        data={[{key:'a'},{key:'b'}]}
       />
      </View>
    );
  }
}

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

//  注意這里引號(hào)中的字符串為本項(xiàng)目的名稱
AppRegistry.registerComponent('OCToRNTestDemo', () => NativeRNApp);

8)在ios工程中,我們需要修改info.plist文件,讀取本地的npm 服務(wù)器
添加如下代碼到info.plist文件中

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

9)在ViewController中導(dǎo)入RCTRootView

#import <React/RCTRootView.h>

在viewDidload方法中,我們把rootView初始化出來(lái),添加到ViewController的view上

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString * strUrl = @"http://localhost:8081/index.ios.bundle?platform=ios&dev=true";
    NSURL * jsCodeLocation = [NSURL URLWithString:strUrl];
    RCTRootView * rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"OCToRNTestDemo" initialProperties:nil launchOptions:nil];
    [self.view addSubview:rootView];
    rootView.frame = CGRectMake(0, 0, 300, 300);
    rootView.center = self.view.center;
}

里面的moduleName為該項(xiàng)目的名字

10)最后運(yùn)行該項(xiàng)目
首先 cd 到RNComponent 文件夾下,輸入:npm start 開(kāi)啟package
開(kāi)啟之后運(yùn)行該ios項(xiàng)目,自此,已經(jīng)把React Native 集成到了iOS原生項(xiàng)目中

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容