React Native之js同步調(diào)用安卓原生方法@ReactMethod(isBlockingSynchronousMethod = true)

1 問題

之前的代碼js調(diào)用安卓原生都是用的異步方法,比如callback, promiss,異步的話,我們一般是在安卓原生有耗時操作,才用異步,如果我要離開返回,就需要js調(diào)用安卓同步方法

利用callback實現(xiàn)js調(diào)用原生可以參考我的這篇博客

React Native實現(xiàn)js調(diào)用安卓原生代碼

React Native之js調(diào)用Android原生使用Callback傳遞結果給js


2  代碼實現(xiàn)

依然在MyToastModule.java文件下面增加下面的同步函數(shù)

        @ReactMethod(isBlockingSynchronousMethod = true)
        public String showMyName() {
            return "chenyu1";
        }

這里用了注解,請注意,也就是說意味著這個方法是同步方法

然后App.js的部分實現(xiàn)如下

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

 
 



 










作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學習,
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎入門進階人工智能(鏈接)