React Native之js调用Android原生使用Callback传递结果给js
生活随笔
收集整理的這篇文章主要介紹了
React Native之js调用Android原生使用Callback传递结果给js
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果不清楚js如何調用Android原生,可以先參考我的這篇博客React Native實現js調用安卓原生代碼
?
?
?
1 問題
上面的文章只是調用安卓原生顯示Toast,但是我們一般會需要調用安卓的代碼然后去拿回結果給js,但是我們知道在android層js調用的這個函數返回值必須的void,所以我們需要用到Callback,這里先說Callback
@ReactMethodpublic void methodName() { }?
?
?
?
2 使用Callback代碼實現
基于我這篇博客里面的 React Native實現js調用安卓原生代碼
的MyToastModule.java文件增加下面這個方法
@ReactMethodpublic 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了
總結
以上是生活随笔為你收集整理的React Native之js调用Android原生使用Callback传递结果给js的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: React Native实现js调用安卓
- 下一篇: Git之submodule使用总结