【问题标题】:How to pass an object back from a React Native Android module to Javascript如何将对象从 React Native Android 模块传回 Javascript
【发布时间】:2017-09-08 22:44:15
【问题描述】:
【问题讨论】:
标签:
javascript
android
react-native
react-native-android
【解决方案1】:
您可以使用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);
}
有关更复杂的数据,请参阅此blog。
【解决方案2】:
对于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);
}
要在 React Native 中调用原生函数,请执行以下操作:
import { NativeModules } from 'react-native';
NativeModules["replaceWithTheModuleName"].test(res => {
console.log(res);
})