Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ネイティブモジュールの作り方 @ React Native Meetup #9 in Japan

ネイティブモジュールの作り方 @ React Native Meetup #9 in Japan

* 作ったネイティブモジュールの紹介
* RNが提供しない事がしたい
* モジュールのセットアップ
* プロジェクトのファイル構成
* helloメソッドの定義
* RNからの呼び出し
* 別スレッドで実行
* 単純なお作法に従うだけ
* でも最終手段

Takuya Matsuyama

September 13, 2018
Tweet

More Decks by Takuya Matsuyama

Other Decks in Programming

Transcript

  1. !3

  2. ϓϩδΣΫτͷϑΝΠϧߏ੒ w ϓϥοτϑΥʔϜ͝ͱʹσΟϨΫτϦ͕༻ҙ͞ΕΔ w ରԠ͠ͳ͍΋ͷ͸࡟আͯ͠Α͍ !8 . ├── android/ ├──

    ios/ ├── windows/ ├── README.md ├── index.js └── package.json 3 directories, 3 files
  3. w RCT_EXPORT_METHODͰϝιουΛΤΫεϙʔτ !10 // ios/RNMyLibrary.m #import "RNMyLibrary.h" @implementation RNMyLibrary RCT_EXPORT_MODULE()

    RCT_EXPORT_METHOD(hello:(NSString *)name) { RCTLogInfo(@"Hello, %@", name); } @end IFMMPϝιουͷఆٛ
  4. IFMMPϝιουͷఆٛ w ۭͬΆͷϞδϡʔϧ !11 // android/src/main/java/com/reactlibrary/RNMyLibraryModule.java package com.reactlibrary; import …;

    public class RNMyLibraryModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public RNMyLibraryModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNMyLibrary"; } }
  5. w @ReactMethodͰϝιουΛΤΫεϙʔτ !12 // android/src/main/java/com/reactlibrary/RNMyLibraryModule.java package com.reactlibrary; import …; public

    class RNMyLibraryModule extends ReactContextBaseJavaModule { private final ReactApplicationContext reactContext; public RNMyLibraryModule(ReactApplicationContext reactContext) { super(reactContext); this.reactContext = reactContext; } @Override public String getName() { return "RNMyLibrary"; } @ReactMethod public void hello(String name) { Log.d("RNMyLibrary", String.format("Hello, %s", name)); } } IFMMPϝιουͷఆٛ
  6. ผεϨουͰ࣮ߦ w ඪ४Ͱϝιου͕࣮ߦ͞ΕΔGCDͷqueueΛࢦఆ methodQueue  w PromiseͰ݁ՌΛฦ͢ !14 - (dispatch_queue_t)methodQueue

    { return dispatch_queue_create(“my.library", DISPATCH_QUEUE_SERIAL); } RCT_EXPORT_METHOD(doSomething:(NSString *)param resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject) { NSArray * result = ...; if (result) { resolve(result); } else { NSError *error = ...; reject(@"my_error", @"Unexpected error", error); } }
  7. ผεϨουͰ࣮ߦ w ThreadͱRunnableΛ࢖͏ w PromiseͰ݁ՌΛฦ͢ !15 @ReactMethod public void doSomething(final

    String param, final Promise promise) { new Thread(new Runnable() { public void run() { // …… promise.resolve(SOMETHING); } catch (Exception e) { promise.reject(“MY_ERROR", e); } } }).start(); }
  8. ݺͼग़͠ w ϝιουͷฦΓ஋͸Promise w async/await͕࢖͑Δ !16 async function doIt() {

    try { var result = await MyLibrary.doSomething('foo'); } catch (e) { console.error(e); } } doIt();