1 问题
之前的代码js调用安卓原生都是用的异步方法,比如callback, promiss,异步的话,我们一般是在安卓原生有耗时操作,才用异步,如果我要离开返回,就需要js调用安卓同步方法
利用callback实现js调用原生可以参考我的这篇博客
React Native实现js调用安卓原生代码
React Native之js调用Android原生使用Callback传递结果给js
2 代码实现
依然在MyToastModule.java文件下面增加下面的同步函数
@ReactMethod(isBlockingSynchronousMethod = true)public String showMyName() {return "chenyu1";}
这里用了注解,请注意,也就是说意味着这个方法是同步方法
然后App.js的部分实现如下
/*** 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>);}_androidShowMsg = () => {var value = myAndroidToast.showMyName();this.setState({myName:value});};
}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 运行结果
点击Welcome to React Native 效果如下