使用自定义原生组件
TCMPP 支持自定义 UI 组件,小程序端的自定义组件为 <external-element>。如果您想使用自定义 UI 组件,请遵循以下步骤:
1. 客户端接入 SDK 后新建继承自 UIView 的类,例如 QMATestView,导入"TMAExternalJSPlugin.h"文件,使 QMATestView 遵循“TMAExternalElementView”协议。
2. 调用 TMARegisterExternalElement 方法,注册 QMATestView 类为 maTestView。
3. 实现“TMAExternalElementView”协议中的 createWithParams 和 operateWithParams 方法。
#import "QMATestView.h"#import "TMAExternalJSPlugin.h"@interface QMATestView () <TMAExternalElementView>@end@implementation QMATestView {UILabel *_textLabel;UIButton *_clickButton;id<TMAExternalJSContextProtocol> _context;}TMARegisterExternalElement(maTestView);+ (UIView *)createWithParams:(NSDictionary *)params context:(id<TMAExternalJSContextProtocol>)context {QMATestView *testView = [[QMATestView alloc] initWithFrame:CGRectZero];NSDictionary *testViewParams = QQ_Dict_DictValue(params, @"params");[testView setText:QQ_Dict_StringValue(testViewParams, @"text")];testView->_context = context;return testView;}//接收小程序端的调用事件进行处理- (void)operateWithParams:(NSDictionary *)param context:(id<TMAExternalJSContextProtocol>)context {NSDictionary *data = QQ_Dict_DictValue(param, @"data");NSDictionary *params1 = QQ_Dict_DictValue(data, @"params1");NSInteger age = [QQ_Dict_NumberValue(params1, @"age") integerValue];NSString *name = QQ_Dict_StringValue(params1, @"name");qq_weakify(self);[MAUtils executeOnThread:[NSThread mainThread] block:^{qq_strongify(self);if (self) {self->_textLabel.text = [NSString stringWithFormat:@"name = %@ , age = %ld",name,(long)age];// 把结果返回给小程序端TMAExternalJSPluginResult *result = [TMAExternalJSPluginResult new];result.result = @{@"result":@"success"};[context doCallback:result];}}];}
发送事件给小程序端
在自定义原生组件里如果想发送事件给小程序端,先在 createWithParams:context: 方法中记录 context:
_context = context;
发送事件时这样写:
- (void)onClickButton:(UIButton *)button {_textLabel.text = @"What do you want me to do";// 组装数据 发送事件NSString *data = [MAUtils JSONStringify:@{@"externalElementId":_elementId,@"type": @"elvisgao callback"}];[_context doSubscribe:kTMAOnExternalElementEvent data:data];}
小程序端使用:
1. 在小程序 wxml 中引入:
<external-elementid="comp1"type="maTestView"_insert2WebLayerstyle="width: 200px;height: 100px;"bindexternalelementevent="handleEvent"></external-element>
说明:
type 需与 native 端约定,如非同层则不设置 _insert2WebLayer 属性。
bindexternalelementevent 可监听 native 传递的操作,回调参数包括:
{target,currentTarget,timeStamp,touches,detail, // native传递的参数}
2. 小程序 js 中创建实例。
this.ctx = wx.createExternalElementContext('comp1');
说明:
wx.createExternalElementContext 参数为 wxml 中元素 id。
3. 在小程序中调用实例方法:
this.ctx.call({params1: {name: 'name1',age: 11},params2: {name: 'name2',age: 22},success: (e) => {console.log('====operate success=====', e)},fail: (e) => {console.log('====operate fail=====', e)},complete: (e) => {console.log('====operate complete=====', e)}})
说明:
实例提供 call 方法,success、fail、complete 回调;通过参数区分调用方法,基础库会调用 invoke 方法透传参数到 native。