如何使用回调编写一个简单的 react-native 本机模块
如何以最简单的方式完成这项工作,我无法将回调发送到 react-native,可能我遗漏了一些东西.
How to get this work, in the simplest way, I have trouble getting the callback send to react-native, probably I'm missing something.
@ReactMethod
public void testCallback(Callback cb) {
String sampleText = "Java is fun";
int textLength = sampleText.length();
try{
cb.invoke(textLength);
}catch (Exception e){
cb.invoke("err");
}
}
在本机方面
var getNativeCallback = require('react-native-native-callback');
getNativeCallback.testCallback(function (result){
console.log(result)
})
我不得不面对同样的问题,最后我不得不采取不同的方法,显然,@ReactProp 没有接受回调类型.
I have to face the same problem, and finally I have to take a different approach, as apparently, there is no Callback type accepted for @ReactProp.
相反,我使用了事件"方式,以便从 Android 原生到 React Native 进行响应通信.
Instead I used the 'Events' way, in order to have response communication from Android native to React Native.
在 Android 端,我设置了一个 SendEvent 函数,可以根据需要方便地触发:
In the Android side I set up a SendEvent function conveniently fired as it needs:
private void sendEventToReactFromAndroid(ReactContext reactContext,String eventName, @Nullable WritableMap params) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
@Override
public void customAndroidListenerFunction() {
sendEvent(mcontext, "EventName", null);
}
然后在 React 端,如果你愿意,你会期待这个事件和参数:
Then in the React side, you will expect this event, and parameters if you may like:
var {DeviceEventEmitter} = require('react-native');
...
componentWillMount: function() {
DeviceEventEmitter.addListener('EventName', function(e: Event) {
console.log("Received event loud and clear in the React Native side!");
});
},
...
希望有所帮助.