简体   繁体   English

React Native如何将数据从JavaScript传递到Java Android

[英]React Native How to pass data from javascript to java android

I followed the tutorial on this site: https://facebook.github.io/react-native/docs/embedded-app-android.html 我遵循了该站点上的教程: https : //facebook.github.io/react-native/docs/embedded-app-android.html

Now I want to have a function in my javascript code like this: 现在,我想在我的JavaScript代码中添加一个像这样的函数:

greetingFunction(){

     return "HELLO, WORLD";
}

I want to pass the string "HELLO, WORLD" to my java android code and set the screen to display that string. 我想将字符串“ HELLO,WORLD”传递给我的Java android代码,并设置屏幕以显示该字符串。

How can I do this? 我怎样才能做到这一点?

You should create a custom module to call custom native methods in Java where you can pass the data you need. 您应该创建一个自定义模块来调用Java中的自定义本机方法,您可以在其中传递所需的数据。

For instance if your custom native module implements the following method: 例如,如果您的自定义本机模块实现以下方法:

@ReactMethod
public void myMethod(String message) {
  // Here we show a toast message
  Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
}

Then you can call that method from JavaScript: 然后,您可以从JavaScript调用该方法:

NativeModules.MyCustomModule.myMethod("HELLO WORLD");

Be sure to properly follow all steps described in the doc above to properly register your custom module. 请务必按照上述文档中所述的所有步骤正确注册您的自定义模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM