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

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

最佳答案

我通过在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()ReactActivityonCreate()方法调用,因此我认为可以安全地假设sReactInstanceManager指向正确的实例,但请不要相信。

关于android - 如何在React Native中了解 “ReactContext”中的 “Sending events to Javascript”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34348519/

10-11 21:34