4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React NativeでNativeのUI Componentを使う(Android編)

Last updated at Posted at 2017-10-18

サードパーティのNative用SDKのコンポーネントをReactNativeで使いたかったので調べた。公式は英語を読めたとしても説明不足だったり、余計だったり分かりづらいと思う。
当方、Android Java初心者ですので悪しからず。プロパティの設定や、他APIの使用はさらに色々設定が必要。
iOS編はこちら。

公式ドキュメント

一番シンプルなコード

  1. Native ComponentのNameとViewインスタンスを返すManagerクラスの作成。
  2. Managerクラス(と他Java module)を取りまとめるPackageの作成。
  3. PackageをMainApplication.javaに登録。
  4. Managerクラスでつけた名前を指定してJavaScriptから呼び出す。
ExampleManager.java
package com.example;

import android.widget.TextView;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;

public class ExampleManager extends SimpleViewManager<TextView> {
    public static final String REACT_CLASS = "Example";

    // Component name that will be called from JavaScript
    @Override
    public String getName() {
        return REACT_CLASS;
    }

    // Return the view component instantiated with Activity context
    @Override
    public TextView createViewInstance(ThemedReactContext reactContext) {
        TextView mTextView = new TextView(reactContext.getCurrentActivity());
        return mTextView;
    }
}

ExamplePackage.java
package com.example;

import java.util.Arrays;
import java.util.List;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

public class ExamplePackage implements ReactPackage {
    // Expose Java components to JavaScript
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
      return Arrays.<ViewManager>asList(
          new ExampleManager()
      );
    }
}

MainApplication.java
public class MainApplication extends Application implements ReactApplication {

    ...

    // Register the new package
    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new ExamplePackage() // New
      );
    }

    ...

}

App.js
import React from 'react';
import { requireNativeComponent } from 'react-native';

const Example = requireNativeComponent('Example', null);

export default class App extends React.Component {
  render() {
    return (
      <Example />
    );
  }
});
4
1
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?