简体   繁体   English

如何将对象从 React Native Android 模块传递回 Javascript

[英]How to pass an object back from a React Native Android module to Javascript

React Native's Native Module documentation for Android says that ReadableMap directly maps to a Javascript object. React Native 的Android 原生模块文档ReadableMap直接映射到 Javascript 对象。 I assume this means that when I pass an object from Javascript to a native module, it is available as a ReadableMap .我认为这意味着当我将对象从 Javascript 传递到本机模块时,它可以作为ReadableMap

How do I do the reverse, which is to create a dictionary (mapping string to string) in a native module and return it to Javascript via a callback ?我如何做相反的事情,即在本机模块中创建一个字典(将字符串映射到字符串)并通过回调将其返回给 Javascript?

You can use WritableMap to simply pass map values through callback.您可以使用WritableMap通过回调简单地传递地图值。

@ReactMethod
public void pass(Callback cb) {
    HashMap<String, String> hm = new HashMap<>();
    hm.put("A", "one");
    hm.put("B", "Two");
    hm.put("C", "Three");
    WritableMap map = new WritableNativeMap();
    for (Map.Entry<String, String> entry : hm.entrySet()) {
        map.putString(entry.getKey(), entry.getValue());
    }
    cb.invoke(map);
}

for more complex data, see this blog .有关更复杂的数据,请参阅此博客

For React Native >=0.62 , you can use this:对于React Native >=0.62 ,你可以使用这个:

import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;

@ReactMethod
public void test(Callback callback) {
    WritableMap map = Arguments.createMap();

    map.putString("yourKey", "yourValue");

    callback.invoke(map);
}

To call the native function in React Native, do this:要在 React Native 中调用本机函数,请执行以下操作:

import { NativeModules } from 'react-native';

NativeModules["replaceWithTheModuleName"].test(res => {
  console.log(res);
})

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

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