如何理解React Native中“向Javascript发送事件”中的“ReactContext”

时间:2015-12-18 04:25:04

标签: android react-native

我想使用sendEvent()方法,但是如何获取ReactContext reactContext?

private void sendEvent(ReactContext reactContext,
                   String eventName,
                   @Nullable WritableMap params) {reactContext
  .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  .emit(eventName, params);}

2 个答案:

答案 0 :(得分:0)

我通过在ReactInstanceManager类上保存MainActivity的静态引用并添加public static getContext()方法来暂时解决了这个问题。它感觉不对,但似乎有效。

public final class MainActivity extends ReactActivity {

    private static ReactInstanceManager sReactInstanceManager = null;

    /* [...] */

    @Override
    protected ReactInstanceManager createReactInstanceManager() {
        ReactInstanceManager manager = super.createReactInstanceManager();
        sReactInstanceManager = manager;
        return manager;
    }

    public static ReactContext getContext() {
        if (sReactInstanceManager == null){
            // This doesn't seem to happen ...
            throw new IllegalStateException("Instance manager not available");
        }
        final ReactContext context = sReactInstanceManager.getCurrentReactContext();
        if (context == null){
            // This really shouldn't happen ...
            throw new IllegalStateException("React context not available");
        }
        return context;
    }

    /* [...] */
}
createReactInstanceManager() ReactActivity方法调用

onCreate(),因此我认为可以安全地假设sReactInstanceManager指向正确的方法例如,但不接受我的话。

答案 1 :(得分:0)

不需要对ReactInstanceManager使用静态引用;您可以致电getReactNativeHost().getReactInstanceManager()来获取它。