React Native之通過(guò)DeviceEventEmitter發(fā)送和接收事件
1 怎么實(shí)現(xiàn)發(fā)送和接收事件
理論上封裝了Android原生廣播的代碼,需要注冊(cè)和反注冊(cè),這里用DeviceEventEmitter實(shí)現(xiàn)
//增加監(jiān)聽(tīng)
DeviceEventEmitter.addListener
//取消監(jiān)聽(tīng)
//this.emitter.remove();
這里可也可以通過(guò)安卓原生向頁(yè)面js發(fā)送消息,可以參考我的這篇博客
React Native之Android原生通過(guò)DeviceEventEmitter發(fā)送消息給js
今天還發(fā)現(xiàn)
const {navigate} = this.props;
等價(jià)于
let navigate = this.props.navigate;
2 測(cè)試代碼
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: '點(diǎn)擊我'};
}
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("收到通知了:內(nèi)容是:" + data);
this.setState({name: data});
});
}
_press = () => {
DeviceEventEmitter.emit('hello', 'chenyu');
}
componentWillUnmount() {
this.emitter.remove();
}
}
3 運(yùn)行結(jié)果
一開(kāi)始的效果
然后 點(diǎn)擊"點(diǎn)擊我"效果如下
然后日志打印如下
ReactNativeJS I 收到通知了:內(nèi)容是:chenyu
作者:chen.yu
深信服三年半工作經(jīng)驗(yàn),目前就職游戲廠商,希望能和大家交流和學(xué)習(xí),
微信公眾號(hào):編程入門(mén)到禿頭 或掃描下面二維碼
零基礎(chǔ)入門(mén)進(jìn)階人工智能(鏈接)