React Native之js调用Android原生使用Callback传递结果给js

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011068702/article/details/82731185

如果不清楚js如何调用Android原生,可以先参考我的这篇博客React Native实现js调用安卓原生代码

 

1 问题

上面的文章只是调用安卓原生显示Toast,但是我们一般会需要调用安卓的代码然后去拿回结果给js,但是我们知道在android层js调用的这个函数返回值必须的void,所以我们需要用到Callback,Callback一般用于同步,也就是说直接调用会直接返回结果,还有一个Promise用于异步,比如我们安卓里面需要写网络请求啥的,等执行完了才返回结果.这里先说Callback

    @ReactMethod
    public void methodName() { 
   
    }

2 使用Callback代码实现

基于我这篇博客里面的 React Native实现js调用安卓原生代码

的MyToastModule.java文件增加下面这个方法

    @ReactMethod
    public void showMyName(Callback result) {
        result.invoke("chenyu");
    }

 

然后App.js文件改定如下,增加了一个构造函数,然后给一个text赋了chenzixuan的值

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

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

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu',
  android:
    'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});
var myAndroidToast = NativeModules.MyToast;
type Props = {};
export default class App extends Component<Props> {
   
    constructor(props){
        super(props);
        this.state={
            myName:'chenzixuan',
        }
    }
  
  render() {
    return (
      <View style={styles.container}>
        <Text onPress={()=> this._androidShowMsg()} style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
        <Text style={styles.instructions}>{this.state.myName}</Text>
      </View>
    );
  }
    /**
     *调用安卓原生代码 
     * @private
     */
    _androidShowMsg = () => {
       myAndroidToast.showMyName((myName)=>{
            this.setState({myName:myName});
        });
    };     

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

3 运行结果

运行之前要记得在项目的目录下执行下面的命令,它会在android的assets目录下生成index.android.bundle文件,也就是安卓会加载这个js文件,这里也会起到编译js作用,如果有语法错误,这里控制台会提示

react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res

然后执行运行项目命令

react-native run-android

第一次运行结果图片如下,下面显示的是chenzixuan

然后我点击Welcome to React Native,下面就显示chenyu了

猜你喜欢

转载自blog.csdn.net/u011068702/article/details/82731185