如何在Android平台上的react-native中调用javascript方法? [英] How to call javascript method in react-native on Android platform?

查看:41
本文介绍了如何在Android平台上的react-native中调用javascript方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击本机 UI 中的按钮(可能来自片段容器)时,我想从 JavaScript 调用一个方法,让我们像 'jsMethod' 或其他一样调用它.不过,我以前从未处理过这种情况.

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.

我正在网站上从Facebook的文档中查找一些相关代码,目前还没有找到问题的关键.有人给我一些建议吗?

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?

推荐答案

要从 Java 调用 JavaScript 方法,请执行以下操作:

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

您要调用的 JavaScript 方法必须被定义并且对 Java 可见:

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

Github 上的这个示例 包括一个工作演示.

EDIT 我听说这种方法没有正式记录.如果您的情况允许,请考虑采纳@ufxmeng 的建议(在 OP 的评论中).

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.

这篇关于如何在Android平台上的react-native中调用javascript方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆