一、 weex调用native
- 在原生的工程里创建一个类继承NSObject
- 遵循WXModuleProtocol协议
- WX_EXPORT_METHOD 暴露方法给JS调用
- WXSDKEngine注册组件(在AppDelegate里注册)
[WXSDKEngine registerModule:@"weexToNative" withClass:[weexToNative class]]
- weex中调用
weex.requireModule("weexToNative").callNative({
native: "i am weex"
});
二、native调用weex
WXSDKInstance是实例级对象非应用级对象,所有只能是接收的实例对象才能调用。
(oc)代码:
[self.instance fireGlobalEvent:@"callJS" params:@{@“1":@"2"}]
(weex)代码
var globalEvent = weex.requireModule('globalEvent')
globalEvent.addEventListener("callWeex", function(e) {
console.log('JS回调了 参数:' + JSON.stringify(e));
});
三、编写原生组件
1.在原生工程中创建一个继承自 WXComponent 的类,以原生的方式在此类中实现组件 ,代码如下
-(instancetype)initWithRef:(NSString *)ref type:(NSString *)type styles:(NSDictionary *)styles attributes:(NSDictionary *)attributes events:(NSArray *)events weexInstance:(WXSDKInstance *)weexInstance
{
if (self = [super initWithRef:ref type:type styles:styles attributes:attributes events:events weexInstance:weexInstance]) {
//设置属性
_titleName = [WXConvert NSString:attributes[@"titleName"]];
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 375, 100)];
[button setTitle:_titleName forState:UIControlStateNormal];
button.backgroundColor = [UIColor blueColor];
[self.view addSubview:button];
}
2.注册原生组件(在AppDelegate中)
[WXSDKEngine registerComponent:@"nativeComponent" withClass:[nativeComponent class]];
3.在weex中调用此组件
<nativeComponent style="height:200px;width:750px;" titleName = "原生组件"></nativeComponent>
具体可看demo
总结:上手相当的简单,基本上没有难理解的地方