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

前端之家收集整理的这篇文章主要介绍了android – 如何理解React Native中“向Javascript发送事件”中的“ReactContext”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想使用方法sendEvent(),但是如何获取ReactContext reactContext?
private void sendEvent(ReactContext reactContext,String eventName,@Nullable WritableMap params) {reactContext
  .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
  .emit(eventName,params);}

解决方法

我通过在MainActivity类上保存对ReactInstanceManager的静态引用,并添加了一个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将指向正确的实例,但不要相信我的话.

猜你在找的Android相关文章