React Native之js調(diào)用Android原生使用Callback傳遞結(jié)果給js
如果不清楚js如何調(diào)用Android原生,可以先參考我的這篇博客React Native實現(xiàn)js調(diào)用安卓原生代碼
上面的文章只是調(diào)用安卓原生顯示Toast,但是我們一般會需要調(diào)用安卓的代碼然后去拿回結(jié)果給js,但是我們知道在android層js調(diào)用的這個函數(shù)返回值必須的void,所以我們需要用到Callback,這里先說Callback
@ReactMethod
public void methodName() {
}
2 使用Callback代碼實現(xiàn)
基于我這篇博客里面的 React Native實現(xiàn)js調(diào)用安卓原生代碼
的MyToastModule.java文件增加下面這個方法
@ReactMethod
public void showMyName(Callback result) {
result.invoke("chenyu");
}
然后App.js文件改定如下,增加了一個構(gòu)造函數(shù),然后給一個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>
);
}
/**
*調(diào)用安卓原生代碼
* @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 運行結(jié)果
運行之前要記得在項目的目錄下執(zhí)行下面的命令,它會在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
然后執(zhí)行運行項目命令
react-native run-android
第一次運行結(jié)果圖片如下,下面顯示的是chenzixuan
然后我點擊Welcome to React Native,下面就顯示chenyu了
作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎(chǔ)入門進階人工智能(鏈接)