React Native JSI:如何从Native调用任何javascript函数



我需要一个回调函数来监听本机模块中的一些事件,并将数据从本机传输到javascript,我想在React native iOS应用程序中直接从本机调用此javascript函数,而不将事件发送到NativeEventEmitter

如何使用JSI(JavaScript接口(实现这一点?

首先,您的函数必须在javascript中全局定义,例如:

App.js

global.greeting = function(param) {
return "Hello " + param + "!";
};

然后您应该在Native:中找到并使用React Native Runtime调用它

AppDelegate.mm

#include <jsi/jsi.h>
#import <React/RCTBridge+Private.h>
using namespace facebook::jsi;
using namespace std;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...

// Runtime notification
[NSNotificationCenter.defaultCenter addObserverForName:RCTJavaScriptDidLoadNotification object:nil queue:nil
usingBlock:^(NSNotification* notification) {
// Get runtime
RCTCxxBridge* cxxbridge = (RCTCxxBridge*)notification.userInfo[@"bridge"];
if (cxxbridge.runtime) {
Runtime& runtime = *(Runtime*)cxxbridge.runtime;

// Get global function
Function greeting = runtime.global().getPropertyAsFunction(runtime, "greeting");

// Call with param
Value param = Value(runtime, String::createFromUtf8(runtime, "JSI"));
Value result = greeting.call(runtime, move(param), 1);

string str = result.asString(runtime).utf8(runtime);
printf("Result: %s", str.c_str());
}
}];
return YES;
}

输出:

Result: Hello JSI!

注意:由于示例使用JSI进行同步本机方法访问,因此不再可能进行远程调试(例如使用Chrome(。相反,您应该使用Flipper来调试JS代码。

最新更新