React Native之通過DeviceEventEmitter發(fā)送和接收事件
1 怎么實現(xiàn)發(fā)送和接收事件
理論上封裝了Android原生廣播的代碼,需要注冊和反注冊,這里用DeviceEventEmitter實現(xiàn)
//增加監(jiān)聽
DeviceEventEmitter.addListener
//取消監(jiān)聽
//this.emitter.remove();
這里可也可以通過安卓原生向頁面js發(fā)送消息,可以參考我的這篇博客
React Native之Android原生通過DeviceEventEmitter發(fā)送消息給js
今天還發(fā)現(xiàn)
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
作者:chen.yu
深信服三年半工作經(jīng)驗,目前就職游戲廠商,希望能和大家交流和學習,
微信公眾號:編程入門到禿頭 或掃描下面二維碼
零基礎入門進階人工智能(鏈接)