Are there any guides for implementing JavaScriptModule in react-native?

前端 未结 2 993
粉色の甜心
粉色の甜心 2020-12-30 11:36

Interested in implementing direct native to javascript calls in react-native. But didn\'t find any guides for that.

Please, help wi

2条回答
  •  说谎
    说谎 (楼主)
    2020-12-30 12:21

    Finally, after looking into react js sources, I figured out the solution, you need to:

    1. Extend JavaScriptModule and pass it to createJSModules method of custom react package (e.g. ActionsModule.java).
    2. Register that package within you react activity getPackages method or directly thought ReactInstanceManager
    3. Create js file with same name in your js code
    4. Register it with BatchedBridge as described in listing below.
    5. Than after react context initialise, you can get it and call via:

      ActionsModule jsModule = context.getJSModule(ActionsModule.class); jsModule.callAction("greet", "hello");

    That will call your registered js module method asynchronously.


    // AppPackage.java
    public class AppPackage implements ReactPackage {
    
        @Override
        public List createNativeModules(ReactApplicationContext reactContext) {
            return Collections.emptyList();
        }
    
        @Override
        public List> createJSModules() {
            return Arrays.>asList(
                    ActionsModule.class
            );
        }
    
        @Override
        public List createViewManagers(ReactApplicationContext reactContext) {
            return Collections.emptyList();
        }
    
    }
    
    // ActionsModule.java
    public interface ActionsModule extends JavaScriptModule {
    
        void callAction(String type, String value);
    
    }
    
    // MyReactActivity.java
    public class MyReactActivity extends ReactActivity implements ReactInstanceManager.ReactInstanceEventListener {
    
        ...
    
        @Override
        public void onReactContextInitialized(ReactContext context) {
            ActionsModule jsModule = context.getJSModule(ActionsModule.class);
    
            jsModule.callAction("greet", "hello");
        }
    
        ...
    
    }
    

    // ActionsModule.js
    var ActionsModule = {
    
      callAction(type, value) {
        console.log("callAction => " + type + ":" + value);
      },
    
    }
    
    module.exports = ActionsModule;
    
    // index.android.js
    import {
      AppRegistry
    } from 'react-native';
    
    import App from './components/App';
    
    // js module registration
    var BatchedBridge = require('BatchedBridge');
    var ActionsModule = require('./ActionsModule');
    
    BatchedBridge.registerCallableModule(
      'ActionsModule',
      ActionsModule
    );
    //~ js module registration
    
    AppRegistry.registerComponent('MyApp', () => App);
    

    UPD> Pushed a demo project to github with a solution for both android and ios: https://github.com/dmba/rct-native2js

提交回复
热议问题