React-Native嵌套原生组件(iOS),包括RN与原生的
这应该是最后一篇关于RN的文章,因为公司决定RN转原生,至于为什么转呢?可能是因为原生才是王道吧!
直入主题:在红色的地方添加一个红色的原生View,之后你可以在这个原生View上面写任何原生控件。包括RN与原生的传参和回调。

一、嵌套原生组件
1.在现有的RN项目中的ios目录中创建一个继承UIView的类

2.再创建一个继承RCTViewManager通讯类

3.在通讯类RNTMLViewManager.m中引入三个头文件
#import "RNTMLView.h"//我们创建的原生View的类
#import <React/RCTBridge.h>//进行通信的头文件
#import <React/RCTEventDispatcher.h>//事件派发,不导入会引起Xcode警告

4.在RNTMLViewManager.m写入RN必要的标记宏
//标记宏(必要)
RCT_EXPORT_MODULE()

5.在RNTMLViewManager.m中创建我们刚刚新建的原生View
- (RNTMLView *)view{
RNTMLView *view = [[RNTMLView alloc] init];
return view;
}

6.创建一个JS文件用来和View做交互

7.在MLView.js中写入这些代码
import React, { Component, PropTypes } from 'react';
var { requireNativeComponent } = require('react-native');
var RNTMLView = requireNativeComponent('RNTMLView', RNTMLView);
export default class MLView extends Component {
render() {
return <RNTMLView {...this.props}/>;
}
}
module.exports = MLView;

8.在需要的地方使用我们的原生View(index.ios.js)引入MLView
import MLView from './MLView';//引入view

9.使用MLView
<MLView width={width} height={height - 44 - 64} backgroundColor={'red'}/>

10运行项目你就可以看到神奇的红色的View出来了

到这里就可以完成一般的项目需求了,但是我们可能还需要暴露出一些回调方法和属性,
ps:实际上这里我们使用了width,height,backgroundColor三个属性,但是我们并没有写相关代码就可以使用,我觉得应该是RN已经帮我们做了一些东西吧,
二、传递参数
11.关于相关的属性的暴露
这里我们测试从RN向原生View传入一个字典(iOS)/对象(js)
首先我们在RNTMLView.h中声明一个字典
@property (nonatomic,strong) NSDictionary *dict;

12.在RNTMLView.m文件中添加set方法监听一下
-(void)setDict:(NSDictionary *)dict{
_dict = dict;
NSLog(@"%@",dict);
}

13.在RNTMLViewManager.m通讯类中添加一个RN通信的宏
RCT_EXPORT_VIEW_PROPERTY(dict, NSDictionary)

13.在MLView.js中添加检测属性的代码
//检测属性
static propTypes = {
width: PropTypes.number,
height: PropTypes.number,
dict: PropTypes.object,
};

14.在使用MLView的地方(index.ios.js)使用dict进行传参
<MLView width={width} height={height - 44 - 64} backgroundColor={'red'} dict={{'毛哥哥':'牛逼'}}/>

15.重新运行xcode,查看是否有打印(当然,肯定是有打印的)

三、点击回调
16.以上就是所有的传参操作,除了传参还有就是输出回调也是很有必要的,实际上跟传参一样的操作
17.模拟一个场景,点击红色的View返回一个字典
18.在RNTMLView.h中引入
#import <React/RCTComponent.h>
19.在RNTMLView.h中添加声明
/**
点击回调
*/
@property (nonatomic, copy) RCTDirectEventBlock onClickBanner;

20.在RNTMLView.m中添加touchesBegan(点击事件)方法来模拟点击回调
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
self.onClickBanner(@{@"牛逼":@"毛哥哥"});
}

21.在RNTMLViewManager.m中添加宏声明
RCT_EXPORT_VIEW_PROPERTY(onClickBanner, RCTBubblingEventBlock)//返回声明

22.在MLView.js文件中添加检测属性
onClickBanner: PropTypes.func,

23.在需要使用的地方使用

24.到这里差不多就可以完成99%项目的需求了,目前我们项目也只涉及到了这些,于是我也没有打算更加深入的往下面研究了。以后我们APP项目全部转原生,可能用到RN的时候应该很少了。但是现在还在开发和维护一个RN前端+node.js后台的个人独立项目,但是不会做过多的原生交互。
ps:期待我的下一篇文章《一个iOS 开发者的自我救赎》,希望能知道迷茫的APP开发者如何让自己更完美,能真正的开发自己的APP(前端+后台)