[ES6-iOSCode]React-Native移植原生iOS項(xiàng)目里

此文章非網(wǎng)上那些直接翻譯沒有經(jīng)過實(shí)踐的文章

項(xiàng)目Demo下載: http://pan.baidu.com/s/1dEZQWyH 密碼: m89h

第一部分:配置處理

1.CocoPods導(dǎo)入相關(guān)依賴庫(kù)(pod上面最新RN版本就0.13.0版本只支持ES5語法)

CocoPods是iOS/Mac開發(fā)中的包管理器,我們需要使用CocoaPods來進(jìn)行下載React Native。(不會(huì)使用pod請(qǐng)百度)
當(dāng)你用CocoaPods進(jìn)行工作的時(shí)候,需要往Podfile文件中添加如下的一些代碼信息,創(chuàng)建Podfile文件命令,先cd iOS項(xiàng)目根目錄再執(zhí)行命令.

touch Podfile

2.Podfile文件寫入相關(guān)代碼

Rn_iostaoge是原生項(xiàng)目名稱

platform :ios, ‘7.0’

target "Rn_iostaoge" do
pod 'React’
pod "React/RCTText"
pod "React/RCTActionSheet"
pod "React/RCTGeolocation"
pod "React/RCTImage"
pod "React/RCTLinkingIOS"
pod "React/RCTNetwork"
pod "React/RCTSettings"
pod "React/RCTVibration"
pod "React/RCTWebSocket"
end

3.創(chuàng)建React Native應(yīng)用(代碼是ES5語法,RN版本太低沒辦法)

創(chuàng)建index.ios.js在根目錄下

touch index.ios.js

index.ios.js寫入以下代碼

'use strict';
 
import React, {
  Text,
  View
} from 'react-native';
 
conststyles = React.StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'red'
  }
});
 
class SimpleApp extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>This is a simple application.</Text>
      </View>
    )
  }
}
 
React.AppRegistry.registerComponent('SimpleApp', () => SimpleApp);

上面代碼中的SimpeApp就是你的模塊名稱,原生iOS建立訪問鏈接的時(shí)候需要

第二部分:iOS原生項(xiàng)目需要做的處理

1.我們需要?jiǎng)?chuàng)建一個(gè)派生類ReactView 名字隨便起

在init...frame方法里寫入

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {

                NSURL *jsLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle"];
                RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsLocation moduleName:@"SimpleApp" initialProperties:nil launchOptions:nil];
                self.rootView = rootView;
                [self addSubview:rootView];
    }
    return self;
    
}

2.在主窗口控制器里ViewDidLoad里聲明載入視圖(具體看Demo)

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    ReactView *rootView = [[ReactView alloc]initWithFrame:CGRectMake(110, 110, 220, 220)];
    
    [self.view addSubview:rootView];
}

3.啟動(dòng)React里的packager

QQ20160719-1@2x.png

cd進(jìn)入react目錄 執(zhí)行以下命令

npm run start 

效果:

QQ20160719-3@2x.png

4.Command+R模擬器走起

效果:

QQ20160719-4@2x.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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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