Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call javascript method in react-native on Android platform?

When I click a button in native UI (probably from a fragment container) , I wanna invoke a method from JavaScript, let's call it just like 'jsMethod' or other else. However, I have never handled this situation before.

I am looking up some relative codes from Facebook's document on website and can not find out the key to the problem so far. Anyone give me some suggestions?

like image 442
fish Avatar asked Sep 04 '17 07:09

fish


1 Answers

To call a JavaScript method from Java, do something like this:

ReactInstanceManager reactInstanceManager = reactNativeHost.getReactInstanceManager();
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();

CatalystInstance catalystInstance = reactContext.getCatalystInstance();
WritableNativeArray params = new WritableNativeArray();
params.pushString("Message to show using nameOfJsMethod");
catalystInstance.callFunction("JavaScriptVisibleToJava", "nameOfJsMethod", params);

The JavaScript method you want to call must be defined and made visible to Java:

import BatchedBridge from "react-native/Libraries/BatchedBridge/BatchedBridge";

export class ExposedToJava {
  nameOfJsMethod(message) {
    alert(message);
  }
}

const exposedToJava = new ExposedToJava();
BatchedBridge.registerCallableModule("JavaScriptVisibleToJava", exposedToJava);

This sample on Github includes a working demo.

EDIT I'm told this approach is not officially documented. If your scenario allows, consider taking the advice of @ufxmeng (in the comment to the OP) instead.

like image 95
Petter Hesselberg Avatar answered Sep 18 '22 15:09

Petter Hesselberg