Dmi*_*try 7 android react-native
有兴趣在react-native 中实现直接本机到javascript调用.但没有找到任何指南.
请帮助一些在本机中创建和注册本机到javascript模块的示例.
已经发现来自官方原生模块android文档的代码有一个名为createJSModules的方法,它返回一个JavaScriptModule类列表.
class AnExampleReactPackage implements ReactPackage {
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
...
}
Run Code Online (Sandbox Code Playgroud)
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 {
}
Run Code Online (Sandbox Code Playgroud)
我能够创建接口并将其传递给createJSModules类,但不知道如何从js代码注册适当的javascript模块.
最后,在查看了反应源后,我想出了解决方案,你需要:
在响应上下文初始化之后,您可以通过以下方式获取并调用:
ActionsModule jsModule = context.getJSModule(ActionsModule.class); jsModule.callAction("greet","hello");
这将异步调用您注册的js模块方法.
// 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");
}
...
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)
UPD>将一个演示项目推向github并提供android和ios的解决方案:https://github.com/dmba/rct-native2js
| 归档时间: |
|
| 查看次数: |
1200 次 |
| 最近记录: |