React Native之通过DeviceEventEmitter发送和接收事件

1 怎么实现发送和接收事件

理论上封装了Android原生广播的代码,需要注册和反注册,这里用DeviceEventEmitter实现
//增加监听
DeviceEventEmitter.addListener
//取消监听
//this.emitter.remove();
这里可也可以通过安卓原生向页面js发送消息,可以参考我的这篇博客

React Native之Android原生通过DeviceEventEmitter发送消息给js

今天还发现

const {navigate} = this.props;

等价于

let navigate = this.props.navigate;

2 测试代码

import React from 'react';
import {View, Text} from 'react-native';
import {DeviceEventEmitter} from "react-native";

export default class App extends React.Component {

       constructor(props) {
          super(props);
          this.state = {name: '点击我'};
       }

       render() {
          return (
            <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
              <Text
          onPress={() => this._press()}
               >{this.state.name}</Text>
            </View>
          );
       }
       componentDidMount() {
           this.emitter = DeviceEventEmitter.addListener("hello", (data) => {
       console.log("收到通知了:内容是:" + data);
       this.setState({name: data});
           });
       }
       _press = () => {
           DeviceEventEmitter.emit('hello', 'chenyu');
       }

       componentWillUnmount() {
           this.emitter.remove();
       }
}

3 运行结果

一开始的效果

然后 点击"点击我"效果如下

然后日志打印如下

ReactNativeJS  I  收到通知了:内容是:chenyu
(0)

相关推荐