[英]How to pass and use data from react native to native android or ios?
我需要將一些數據形式傳遞給原生 android 和 ios。
我怎樣才能做到這一點?
謝謝,
如果你想在 React Native 應用程序中與 natives 模塊通信,你應該看看這些 Native Modules 的例子。 這是針對 ioshttps://facebook.github.io/react-native/docs/native-modules-ios而這是針對 android https://facebook.github.io/react-native/docs/native-modules-安卓
您可以創建一個需要參數的本機方法,如下所示:
@ReactMethod
public void createCalendarEvent(String name, String location) {
Log.d("CalendarModule", "Create event called with name: " + name
+ " and location: " + location);
}
本機端接收其參數並在本機方法中使用它:
CalendarModule.createCalendarEvent('testName', 'testLocation');
這個問題是一年前的,但也許有人仍然想知道如何從 react native 傳遞到 native (android)。 我從David Vittori
那里找到了答案,確實有文檔。
為了簡化您可以執行此步驟:
public class ExamplePackage implements ReactPackage {
@Nonnull
@Override
public List<ViewManager> createViewManagers(@Nonnull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
@Nonnull
@Override
public List<NativeModule> createNativeModules(@Nonnull ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ExampleModule(reactContext));
return modules;
}
}
(native android) 然后在MainApplication.java
,在getPackages()
方法中添加:
packages.add(new ExamplePackage());
(native android) 創建像ExampleModule.java
這樣的 java 類:
public class ExampleModule extends ReactContextBaseJavaModule {
Activity activity;
public ExampleModule(@Nonnull ReactApplicationContext reactContext) {
super(reactContext);
}
@Nonnull
@Override
public String getName() {
return "ExampleModule";
}
@ReactMethod(isBlockingSynchronousMethod = true)
public void MinimizeExample(String params) {
activity = getCurrentActivity();
Toast.makeText(getReactApplicationContext(), "triggered by react native with params: " + params, Toast.LENGTH_LONG).show();
}
}
import { NativeModules } from "react-native";
const { ExampleModule } = NativeModules;
const ExampleDetail = ({ navigation }) => {
const onButtonPressed = () => {
ExampleModule.MinimizeExample("passing params to native android");
};
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.