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

2 javascript android react-native react-native-android

React Native 针对AndroidNative Module文档ReadableMap直接映射到Javascript对象。我认为这意味着当我将对象从Javascript传递到本机模块时,它可以作为ReadableMap

我该如何反向操作,即在本机模块中创建字典(将字符串映射为字符串),然后通过回调将其返回给Javascript ?

ufx*_*eng 6

您可以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);
}
Run Code Online (Sandbox Code Playgroud)

有关更复杂的数据,请参见此博客


fad*_*ayo 6

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

要在 React Native 中调用本机函数,请执行以下操作:

import { NativeModules } from 'react-native';

NativeModules["replaceWithTheModuleName"].test(res => {
  console.log(res);
})
Run Code Online (Sandbox Code Playgroud)