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
ReactNative 效果如下