簡體   English   中英

如何將數據從 react native 傳遞到 native android 或 ios?

[英]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那里找到了答案,確實有文檔。

為了簡化您可以執行此步驟:

  1. (原生android)像這樣創建java類:
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;
    }
}
  1. (native android) 然后在MainApplication.java ,在getPackages()方法中添加:

    packages.add(new ExamplePackage());

  2. (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();
        }
    }
  1. 最后在你的 React Native 中,無論是將它放在屏幕上還是組件上,都可以像這樣調用方法:
    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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM