React Native调用Android原生方法的项目实现

2020-09-0922:40:05WEB前端开发Comments2,047 views字数 3962阅读模式

1、项目基于React Native 0.63.2版本,使用命令react-native init rn_native新建工程项目

2、以下使用弹窗方式来说明rn如何调用原生方法

3、android目录下新建react包

React Native调用Android原生方法的项目实现

创建AlertModule.java RnNativeReactPackage.java文件;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

4、下面开始具体的实现

1、AlertModule.java 文件:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

import android.app.AlertDialog;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

public class AlertModule extends ReactContextBaseJavaModule {
    private ReactApplicationContext mContext;
    public AlertModule(ReactApplicationContext reactContext){
        super(reactContext);
        mContext = reactContext;
    }
    @NonNull
    @Override
    public String getName() {
        return "AlertModule";   //js中调用该模块需要用的名称
    }
    @ReactMethod
    public void toast(String message){
        //注解 :@ReactMethod  js中可调用的方法
        Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
    @ReactMethod
    public void alert(String title,String message){
        AlertDialog.Builder tDialog = new AlertDialog.Builder(getCurrentActivity());
        tDialog.setTitle(title);
        tDialog.setMessage(message);
        tDialog.setPositiveButton("确定", null);
        tDialog.setNegativeButton("取消",null);
        tDialog.show();
    }
}
复制代码

AlertModule类继承ReactContextBaseJavaModule,其中getName()方法 返回的名称是 JavaScript 中调起这个模块的名称,js实际调用这个模块 如:const Alert = NativeModules.AlertModule ;注解: @ReactMethod ,如果你想写一个js中调用的方法需在方法前面加上@ReactMethod,这样js中可通过文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

const Alert = NativeModules.AlertModule
Alert.toast();
复制代码

调用文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

2、RnNativeReactPackage.java文件:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

package com.rn_native.react;

import androidx.annotation.NonNull;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RnNativeReactPackage implements ReactPackage {
    @NonNull
    @Override
    public List<NativeModule> createNativeModules(@NonNull ReactApplicationContext reactContext) {
        List<NativeModule> modules = new ArrayList<>();

        modules.add(new AlertModule(reactContext));
        return modules;
    }

    @NonNull
    @Override
    public List<ViewManager> createViewManagers(@NonNull ReactApplicationContext reactContext) {
        return  Collections.emptyList();
    }
}

复制代码

这个文件主要是注册AlertModule模块,如果模块没有被注册,在js是无法被访问的(这个动作很多时候会忘记);如果后续你自己新建了一个模块TestModule,则文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

······
  modules.add(new AlertModule(reactContext));
  modules.add(new TestModule(reactContext));
......
复制代码

3、接下来这一步也很重要:MainApplication.java文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

 
......

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
          return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {

          List<ReactPackage> packages = new PackageList(this).getPackages();
 
            packages.add(new RnNativeReactPackage());    
          return packages;
        }

        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
      };
......
}

复制代码

RnNativeReactPackage package加到MainApplication.java文件的getPackages方法中;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

至此Android原生部分已完成,接下来说明js中如何使用;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

App.js文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

import React from 'react';
import {
  StyleSheet,
  View,
  Text,
  TouchableOpacity,
  NativeModules,
} from 'react-native';

const Alert = NativeModules.AlertModule;
export default class App extends React.Component {
  _toast = () => {
    Alert.toast('我调用了原生的toast方法');
  };
  _alert = () => {
    Alert.alert('title', '我调用了原生的Alert方法');
  };
  render() {
    return (
      <View style={styles.center}>
        <TouchableOpacity onPress={this._toast} style={styles.toastTou}>
          <Text style={styles.titleText}>调用原生的toast</Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={this._alert}
          style={[styles.toastTou, {marginTop: 30}]}>
          <Text style={styles.titleText}>调用原生的Alert</Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toastTou: {
    width: 200,
    height: 40,
    borderRadius: 20,
    backgroundColor: 'green',
    alignItems: 'center',
    justifyContent: 'center',
  },
  titleText: {
    fontSize: 14,
    color: '#fff',
  },
});

复制代码

第一步在js中const Alert = NativeModules.AlertModule; AlertModule就是原生中getName返回的模块名称,声明模块;文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

第二步调用方法Alert.toast('我调用了原生的toast方法'); Alert.alert('title', '我调用了原生的Alert方法'); 调用原生自定的方法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

以上便实现了react native调用Android原生方法!文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

作者:各个法文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/20193.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/20193.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定