参考:React-Native 发送和接收事件DeviceEventEmitter
005-React-Native子组件修改父组件的几种方式,兄弟组件状态修改
我想要实现的功能,是点击子类中的一个按钮,在父类中弹出一个MODAL。要求是:在单击子类按钮的时候,需要向父类传参,告诉父类单击的是哪个按钮,根据按钮的不同,显示不同的modal。使用组件DeviceEventEmitter实现传参。
1.在父类和子类中都需要导入DeviceEventEmitter组件:
import {View,Text,Button,DeviceEventEmitter}from 'react-native';
2.在子类中写一个发送消息的方法:
<Button title="发送通知" onPress={() => {DeviceEventEmitter.emit('left','发送了个通知');}}/>
3.在父类中写一个接收这个消息的方法:
在didmount方法中写好监听/接收方法,当有消息发送时,这就会接收到,并执行相应方法:
componentDidMount() {this.deEmitter =DeviceEventEmitter.addListener('left', (a) => { alert('收到通知:' + a); });}
4.最后在父类中,需要卸载监听:
componentWillUnmount() {this.deEmitter.remove();}
网友评论