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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。