如何使用回调编写简单的react-native本机模块

sya*_*rul 5 android react-native

如何以最简单的方式完成这项工作,我无法将回调发送到本地反应,可能是我遗漏了一些东西.

@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");
    }
}
Run Code Online (Sandbox Code Playgroud)

在反应原生方面

var getNativeCallback = require('react-native-native-callback');


getNativeCallback.testCallback(function (result){
    console.log(result)
})
Run Code Online (Sandbox Code Playgroud)

小智 3

我必须面对同样的问题,最后我必须采取不同的方法,显然,@ReactProp 不接受回调类型。

相反,我使用“事件”方式,以便从 Android 本机到 React Native 进行响应通信。

在 Android 端,我设置了一个 SendEvent 函数,可以根据需要方便地触发:

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);

}
Run Code Online (Sandbox Code Playgroud)

然后在 React 端,您将期望此事件和参数(如果您愿意):

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!");
    });
},
...
Run Code Online (Sandbox Code Playgroud)

希望有帮助。