ReactNative前端与原生事件交互----原生向JavaScript端发送事件

一、点击页面按钮,原生向JavaScript端发送事件

第一步:创建MyModule

public class MyModule extends ReactContextBaseJavaModule {

    public MyModule(ReactApplicationContext reactContext) {

        super(reactContext);

        //给上下文对象赋值
        Test.myContext=reactContext;
    }

    @Override
    public String getName() {

        return "MyModule";
    }


    @ReactMethod
    public void  NativeMethod()
    {
        //调用Test类中的原生方法。
        new Test().fun();
    }
}

第二步:创建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();
    }
}

第三步:创建Test

public class Test {

     //定义上下文对象
    public static ReactContext myContext;

    //定义发送事件的函数
    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端发送事件。
        new Thread(new Runnable() {
            @Override
            public void run() {

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

               //发送事件,事件名为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(){  
                      //监听事件名为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: '这个是预定的接受信息',
    }
}

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

        <Text style={styles.welcome}
         onPress={this.callNative.bind(this)}
        >
          当你点我的时候会调用原生方法,原生方法延迟3s后会向前端发送事件。
          前端一直在监听该事件,如果收到,则给出alert提示!
        </Text>
        
        <Text style={styles.welcome} >
        {this.state.content}
         </Text>


      </View>
    );
  }

  callNative()
  {
    NativeModules.MyModule.NativeMethod();
  }
 
  showState()
  {
       this.setState({content:'已经收到了原生模块发送来的事件'})
  }
}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 大部分的后端会很很鄙视前端。我也不知道为什么,可能大部分人都会觉得脚本语言根本不算语言。 大多人 会叫我们切图仔,...
    小黑的眼阅读 3,507评论 0 15
  • 前些日子从@张鑫旭微博处得一份推荐(Front-end-tutorial),号称最全的资源教程-前端涉及的所有知识...
    谷子多阅读 4,325评论 0 44
  • 回校以来,家人都会出现在梦里。今天最奇怪的梦(可能其他的忘了)是和哥哥一起参加自行车比赛。 在山间的路上比赛,比赛...
    风雪7缘阅读 173评论 0 0
  • 今日立冬,冬天已破门而入。门外,还依稀可见秋落叶纷飞的背影。 尽管如此喜欢秋,但冬天来了,就思慕着冬天吧,触摸冬天...
    如月如月阅读 1,052评论 6 15
  • 我知道自己一定活不下去了。过度使用的写轮眼已经一片模糊,透支的查克拉连一个火遁都发不出来,至少三种致命伤,即使最好...
    苍烟落照阅读 379评论 0 1