有兴趣在react-native中实现直接本机到
javascript调用.但没有找到任何指南.
请帮助一些在本机中创建和注册本机到javascript模块的示例.
已经发现官方native modules android文档中的代码有一个名为createJSModules的方法,它返回一个JavaScriptModule类列表.
class AnExampleReactPackage implements ReactPackage { @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } ... }
com.facebook.react.bridge.JavaScriptModule的Javadoc说:
/** * Interface denoting that a class is the interface to a module with the same name in JS. Calling * functions on this interface will result in corresponding methods in JS being called. * ... */ @DoNotStrip public interface JavaScriptModule { }
解决方法
最后,在查看了反应源后,我想出了解决方案,你需要:
>扩展JavaScriptModule并将其传递给自定义反应包的createJSModules方法(例如ActionsModule.java).
>在您内部注册包反应活动getPackages方法或直接认为ReactInstanceManager
>在js代码中创建具有相同名称的js文件
>按照下面列出的说明将其注册到BatchedBridge.
>在响应上下文初始化之后,您可以通过以下方式获取并调用:
ActionsModule jsModule = context.getJSModule(ActionsModule.class);
jsModule.callAction(“greet”,“hello”);
// AppPackage.java public class AppPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List<Class<? extends JavaScriptModule>> createJSModules() { return Arrays.<Class<? extends JavaScriptModule>>asList( ActionsModule.class ); } @Override public List<ViewManager> 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>将一个演示项目推向了github,并提供了android和ios的解决方案:https://github.com/dmba/rct-native2js