官方example如下:
public class UIManagerModule extends ReactContextBaseJavaModule {
...
@ReactMethod
public void measureLayout(
int tag,
int ancestorTag,
Callback errorCallback,
Callback successCallback) {
try {
measureLayout(tag, ancestorTag, mMeasureBuffer);
float relativeX = PixelUtil.toDIPFromPixel(mMeasureBuffer[0]);
float relativeY = PixelUtil.toDIPFromPixel(mMeasureBuffer[1]);
float width = PixelUtil.toDIPFromPixel(mMeasureBuffer[2]);
float height = PixelUtil.toDIPFromPixel(mMeasureBuffer[3]);
successCallback.invoke(relativeX, relativeY, width, height);
} catch (IllegalViewOperationException e) {
errorCallback.invoke(e.getMessage());
}
}
...
callback的实现是CallbackImpl,code如下:
public final class CallbackImpl implements Callback {
private final JSInstance mJSInstance;
private final int mCallbackId;
private boolean mInvoked;
public CallbackImpl(JSInstance jsInstance, int callbackId) {
mJSInstance = jsInstance;
mCallbackId = callbackId;
mInvoked = false;
}
@Override
public void invoke(Object... args) {
if (mInvoked) {
throw new RuntimeException("Illegal callback invocation from native "+
"module. This callback type only permits a single invocation from "+
"native code.");
}
mJSInstance.invokeCallback(mCallbackId, Arguments.fromJavaArgs(args));
mInvoked = true;
}
}
JSInstance的实现是CatalystInstanceImpl,
@Override
public void invokeCallback(final int callbackID, final NativeArray arguments) {
if (mDestroyed) {
FLog.w(ReactConstants.TAG, "Invoking JS callback after bridge has been destroyed.");
return;
}
jniCallJSCallback(callbackID, arguments);
}
然后会调用CatalystInstanceImpl.cpp中的jniCallJSCallback
instance_->callJSCallback(callbackId, arguments->consume());
之后会调用Instance.cpp
void Instance::callJSCallback(uint64_t callbackId, folly::dynamic &¶ms) {
SystraceSection s("Instance::callJSCallback");
callback_->incrementPendingJSCalls();
nativeToJsBridge_->invokeCallback((double)callbackId, std::move(params));
}
然后就是native发到JS,进行触发相应的方法了。
网友评论