ReactNative前端與原生事件交互----原生向JavaScript端發(fā)送事件

一、點(diǎn)擊頁面按鈕,原生向JavaScript端發(fā)送事件

第一步:創(chuàng)建MyModule

public class MyModule extends ReactContextBaseJavaModule {

    public MyModule(ReactApplicationContext reactContext) {

        super(reactContext);

        //給上下文對(duì)象賦值
        Test.myContext=reactContext;
    }

    @Override
    public String getName() {

        return "MyModule";
    }


    @ReactMethod
    public void  NativeMethod()
    {
        //調(diào)用Test類中的原生方法。
        new Test().fun();
    }
}

第二步:創(chuàng)建MyPackage

public class MyPackage implements ReactPackage {
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {

        List<NativeModule> modules=new ArrayList<>();
        modules.add(new MyModule(reactContext));

        return modules;
    }

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

第三步:創(chuàng)建Test

public class Test {

     //定義上下文對(duì)象
    public static ReactContext myContext;

    //定義發(fā)送事件的函數(shù)
    public  void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params)
    {
        System.out.println("reactContext="+reactContext);

        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName,params);
    }

    public  void fun()
    {
        //在該方法中開啟線程,并且延遲3秒,然后向JavaScript端發(fā)送事件。
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

               //發(fā)送事件,事件名為EventName
                WritableMap et= Arguments.createMap();
                sendEvent(myContext,"EventName",et);


            }
        }).start();

    }


}


第四步:index.android.js中處理

import React, { Component } from 'react';
import {
 AppRegistry,
  StyleSheet,
  Text,
  DeviceEventEmitter,
  NativeModules,
  View
} from 'react-native';

export default class ReactAndroid extends Component {

    componentWillMount(){  
                      //監(jiān)聽事件名為EventName的事件
                    // DeviceEventEmitter.addListener('EventName', function() {  
                         
                    //      this.showState();

                    //      alert("send success");  
                    //      // this.showState();

                    //    }); 

                    DeviceEventEmitter.addListener('EventName', ()=> {  
                         
                         this.showState();
                         alert("send success");  

                       }); 
                
}

  constructor(props) {
    super(props);
    this.state = {
        content: '這個(gè)是預(yù)定的接受信息',
    }
}

  render() {
    return (
      <View style={styles.container}>

        <Text style={styles.welcome}
         onPress={this.callNative.bind(this)}
        >
          當(dāng)你點(diǎn)我的時(shí)候會(huì)調(diào)用原生方法,原生方法延遲3s后會(huì)向前端發(fā)送事件。
          前端一直在監(jiān)聽該事件,如果收到,則給出alert提示!
        </Text>
        
        <Text style={styles.welcome} >
        {this.state.content}
         </Text>


      </View>
    );
  }

  callNative()
  {
    NativeModules.MyModule.NativeMethod();
  }
 
  showState()
  {
       this.setState({content:'已經(jīng)收到了原生模塊發(fā)送來的事件'})
  }
}

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,
  },
});

AppRegistry.registerComponent('ReactAndroid', () => ReactAndroid);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 大部分的后端會(huì)很很鄙視前端。我也不知道為什么,可能大部分人都會(huì)覺得腳本語言根本不算語言。 大多人 會(huì)叫我們切圖仔,...
    小黑的眼閱讀 3,607評(píng)論 0 15
  • 前些日子從@張?chǎng)涡裎⒉┨幍靡环萃扑](Front-end-tutorial),號(hào)稱最全的資源教程-前端涉及的所有知識(shí)...
    谷子多閱讀 4,485評(píng)論 0 44
  • 回校以來,家人都會(huì)出現(xiàn)在夢(mèng)里。今天最奇怪的夢(mèng)(可能其他的忘了)是和哥哥一起參加自行車比賽。 在山間的路上比賽,比賽...
    風(fēng)雪7緣閱讀 199評(píng)論 0 0
  • 今日立冬,冬天已破門而入。門外,還依稀可見秋落葉紛飛的背影。 盡管如此喜歡秋,但冬天來了,就思慕著冬天吧,觸摸冬天...
    如月如月閱讀 1,138評(píng)論 6 15
  • 我知道自己一定活不下去了。過度使用的寫輪眼已經(jīng)一片模糊,透支的查克拉連一個(gè)火遁都發(fā)不出來,至少三種致命傷,即使最好...
    蒼煙落照閱讀 396評(píng)論 0 1

友情鏈接更多精彩內(nèi)容