微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

 

 

 

1 问题

上面的文章只是调用安卓原生显示Toast,但是我们一般会需要调用安卓的代码然后去拿回结果给js,但是我们知道在android层js调用的这个函数返回值必须的void,所以我们需要用到Callback,这里先说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了

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐