React Native iOS相互调用
2018-08-09 本文已影响127人
1234yws
打开iOS工程
- 在你需要用React Native 的地方添加UIButton
- 创建react native 的容器view
#import <UIKit/UIKit.h>
@interface ReactView : UIView
@end
#import "ReactView.h"
#import <React/RCTRootView.h>// 导入reactView
@implementation ReactView
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
NSURL *jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];
RCTRootView *rootView =
[[RCTRootView alloc] initWithBundleURL: jsCodeLocation
moduleName: @"MyApp"
initialProperties:nil
launchOptions: nil];
[self addSubview:rootView];
rootView.frame = self.bounds;
}
return self;
}
@end
项目目录下找到index.js
我是通过sublime Text 3 编写的,推荐几个适合React-native的插件
react-native-snippets
ReactJS
index.js作为一个类似main函数,所以以简洁为准
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity
} from 'react-native';
import Root from './App/root';
// MyApp 必须要和工程里边的moduleName:一致
/*
- (instancetype)initWithBridge:(RCTBridge *)bridge
moduleName:(NSString *)moduleName
initialProperties:(NSDictionary *)initialProperties NS_DESIGNATED_INITIALIZER;
*/
AppRegistry.registerComponent('MyApp', () => Root);
在目录中创建App文件夹并且创建root.js文件作为根文件
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
NativeModules,
Button,
Alert,
} from 'react-native';
var WSReactRout = NativeModules.WSReactRout;
export default class MyApps extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
<View style={styles.buttonContainer}>
<Button
onPress={this._onPressButton}
title="Press Me"
style={styles.container}
/>
</View>
</View>
);
}
_onPressButton() {
WSReactRout.WSJumpToVC('YWS');
}
}
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,
},
buttonContainer: {
margin: 20
},
});
在Xcode创建一个文件继承NSObject
.h 文件
#import <Foundation/Foundation.h>
#import <React/RCTBridgeModule.h>
#import <React/RCTLog.h>
@interface WSReactRout : NSObject<RCTBridgeModule>
@end
.m文件
#import "WSReactRout.h"
@implementation WSReactRout
RCT_EXPORT_MODULE()
//RN跳转原生界面
RCT_EXPORT_METHOD(WSJumpToVC:(NSString *)msg){
NSLog(@"RN传入原生界面的数据为:%@",msg);
}
// 接收传过来的 NSString
RCT_EXPORT_METHOD(addEventOne:(NSString *)name){
NSLog(@"接收传过来的NSString+NSString: %@", name);
//进行页面跳转
}
@end